home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 5 / Skunkware 5.iso / lib / calc / cryrand.cal < prev    next >
Text File  |  1995-07-17  |  83KB  |  2,552 lines

  1. /*
  2.  * cryrand - cryptographically strong pseudo-random number generator library
  3.  */
  4. /*
  5.  * Copyright (c) 1993 by Landon Curt Noll.  All Rights Reserved.
  6.  *
  7.  * Permission to use, copy, modify, and distribute this software and
  8.  * its documentation for any purpose and without fee is hereby granted,
  9.  * provided that the above copyright, this permission notice and text
  10.  * this comment, and the disclaimer below appear in all of the following:
  11.  *
  12.  *    supporting documentation
  13.  *    source copies
  14.  *    source works derived from this source
  15.  *    binaries derived from this source or from derived source
  16.  *
  17.  * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
  18.  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
  19.  * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
  20.  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  21.  * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  22.  * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  23.  * PERFORMANCE OF THIS SOFTWARE.
  24.  *
  25.  * chongo was here    /\../\
  26.  */
  27.  
  28. /*
  29.  * These routines are written in the calc language.  At the time of this
  30.  * notice, calc was at version 1.24.7 (We refer to calc, as in the C 
  31.  * program, not the Emacs subsystem).
  32.  *
  33.  * Calc is available by anonymous ftp from ftp.uu.net (137.39.1.9)
  34.  * under the directory /pub/calc.
  35.  *
  36.  * If you can't get calc any other way, Email a request to my Email
  37.  * address as shown below.
  38.  *
  39.  * Comments, suggestions, bug fixes and questions about these routines 
  40.  * are welcome.  Send Email to the address given below.
  41.  *
  42.  * Happy bit twiddling,
  43.  *
  44.  *            Landon Curt Noll
  45.  *
  46.  *            chongo@toad.com 
  47.  *            ...!{pyramid,sun,uunet}!hoptoad!chongo
  48.  */
  49.  
  50. /*
  51.  * AN OVERVIEW OF THE FUNCTIONS:
  52.  *
  53.  * This calc library contains several pseudo-random number generators:
  54.  *
  55.  *   additive 55:
  56.  *
  57.  *    a55rand      - external interface to the additive 55 generator
  58.  *    sa55rand  - seed the additive 55 generator
  59.  *
  60.  *    This is a generator based on the additive 55 generator as
  61.  *    described in Knuth's "The Art of Computer Programming -
  62.  *    Seminumerical Algorithms", vol 2, 2nd edition (1981),
  63.  *    Section 3.2.2, page 27, Algorithm A.
  64.  *
  65.  *    The period and other properties of this generator make it very
  66.  *    useful to 'seed' other generators.  
  67.  *
  68.  *    This generator is used by other other generators to produce
  69.  *    various internal values.  In fact, the lower 64 bits of seed
  70.  *    given to other other generators is passed to sa55rand().
  71.  *
  72.  *   shuffle:
  73.  *
  74.  *    shufrand  - generate a pseudo-random value via a shuffle process
  75.  *    sshufrand - seed the shufrand generator
  76.  *    rand      - generate a pseudo-random value over a given range
  77.  *    srand     - seed the random stream generator
  78.  *
  79.  *    This is a generator based on the shuffle generator as described in
  80.  *    Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  81.  *    vol 2, 2nd edition (1981), Section 3.2.2, page 32, Algorithm B.
  82.  *
  83.  *    The shuffle generator is fast and serves as a fairly good standard 
  84.  *    pseudo-random generator.
  85.  *
  86.  *    The shuffle generator is feed random values by the additive 55
  87.  *    generator via a55rand().  Calling a55rand() or sa55rand() will
  88.  *    affect the shuffle generator output.
  89.  *
  90.  *    The rand function is really another interface to the shuffle
  91.  *    generator.  Unlike shufrand(), rand() can return a value of any
  92.  *    given size.  The value returned by rand() may be confined to
  93.  *    either a half open [0,a) (0 <= value < a) or closed interval
  94.  *    [a,b] (a <= value <= b).  By default, a 64 bit value is returned.
  95.  *
  96.  *    Calling srand() simply calls sshufrand() with the same seed.
  97.  *
  98.  *   crypto:
  99.  *
  100.  *    cryrand   - produce a cryptographically strong pseudo-random number
  101.  *    scryrand  - seed the crypto generator
  102.  *    random    - produce a cryptographically strong pseudo-random number
  103.  *            over a given range
  104.  *     srandom   - seed random
  105.  *
  106.  *    This generator is described in the papers:
  107.  *
  108.  *        Blum, Blum, and Shub, "Comparison of Two Pseudorandom Number
  109.  *        Generators", in Chaum, D. et. al., "Advances in Cryptology:
  110.  *        Proceedings Crypto 82", pp. 61-79, Plenum Press, 1983.
  111.  *
  112.  *        "Probabilistic Encryption", Journal of Computer & System
  113.  *        Sciences 28, pp. 270-299.
  114.  *
  115.  *    We also refer to this generator as the 'Blum' generator.
  116.  *
  117.  *    This generator is considered 'strong' in that it passes all
  118.  *    polynomial-time statistical tests.  This means that there
  119.  *    is no statistical test, which runs in polynomial time, that 
  120.  *    can distinguish the crypto generator from a truly random source.
  121.  *
  122.  *    The crypto generator is not as fast as most generators, though 
  123.  *    it is not painfully slow either.
  124.  *
  125.  *    One may fully seed this generator via scryrand().  Calling
  126.  *    scryrand() with 1 or 3 arguments will result in the additive
  127.  *    55 generator being seeded with the same seed.  Calling
  128.  *     scryrand() with 4 arguments, where the first argument 
  129.  *    is >= 0 will also result in the additive 55 generator
  130.  *    being seeded with the same seed.
  131.  *
  132.  *    The random() generator is really another interface to the
  133.  *    crypto generator.  Unlike cryrand(), random() can return a
  134.  *    value confined to either a half open (0 <= value < a) or closed
  135.  *    interval (a <= value <= b).  By default, a 64 bit value is
  136.  *    returned.
  137.  *
  138.  *    Calling srandom() simply calls scryrand(seed).  The additive
  139.  *    55 generator will be seeded with the same seed.
  140.  *
  141.  * All generators come already seeded with precomputed initial constants.
  142.  * Thus, it is not required to seed a generator before using it.
  143.  *
  144.  * Using a seed of '0' will reload generators with their initial states.
  145.  * In the case of scryrand(), lengths of -1 must also be supplied.
  146.  *
  147.  *    sa55rand(0)
  148.  *    sshufrand(0)
  149.  *    srand(0)
  150.  *    scryrand(0,-1,-1)
  151.  *    srandom(0)
  152.  *    scryrand(-1,ip,iq,ir)
  153.  *
  154.  * All of the above 'seed 0' calls are fairly fast.  In fact, passing
  155.  * seeding with a non-zero seed, in the above cases, where seed is
  156.  * not excessively large (many bits long), is also reasonably fast.
  157.  * The 4 arg scryrand() call is fairly fast because no checking is
  158.  * performed on the 'ip', 'iq', or 'ir' values.
  159.  *
  160.  * A call of scryrand(seed,len1,len2), with len1,len2 > 4, (3 args)
  161.  * is a somewhat slow as the length args increase.  This type of
  162.  * call selects 2 primes that are used internally by the crypto
  163.  * generator.  A call of scryrand(seed,ip,iq,ir) where seed >= 0
  164.  * is as slow as the 3 arg case.  See scryrand() for more information.
  165.  *
  166.  * A call of scryrand() (no args) may be used to quickly change the 
  167.  * internal state of the crypto and random generators.  Only one major 
  168.  * internal crypto generator value (a quadratic residue) is randomly 
  169.  * selected via the additive 55 generator.  The other 2 major internal 
  170.  * values (the 2 Blum primes) are preserved.  In this form, the additive 
  171.  * 55 is not seeded.
  172.  *
  173.  * Calling scryrand() with 1 or 3 args, or calling srandom() will leave
  174.  * the additive 55 generator in a seeded state as if sa55rand(seed) has
  175.  * been called.  Calling scryrand() with 4 args, where the first arg is 
  176.  * >0 will also leave the additive 55 generator in the same scryrand(seed)
  177.  * state.  Calling scryrand() with no args will not seed the additive
  178.  * 55 generator before or afterwards, however the additive 55 and shuffle
  179.  * generators will be changed as a side effect of that call.
  180.  *
  181.  * The states of all generators (additive 55, shuffle and crypto) can be 
  182.  * saved and restored via the randstate() function.  Saving the state just 
  183.  * after * seeding a generator and restoring it later as a very fast way 
  184.  * to reseed a generator.
  185.  *
  186.  * As a bonus, the function 'nxtprime' is provided to produce a probable
  187.  * prime number.
  188.  *
  189.  * TRUTH IN ADVERTISING:
  190.  *
  191.  * The word 'probable', in reference to the nxtprime() function, is used 
  192.  * because of an extremely extremely small chance that a composite (a
  193.  * non-prime) may be returned.  In no cases will a prime be skipped.  
  194.  * For our purposes, this is sufficient as the chance of returning a 
  195.  * composite is much smaller than the chance that a hardware glitch
  196.  * will cause nxtprime() to return a bogus result.
  197.  *
  198.  * Another "truth in advertising" issue is the use of the term 
  199.  * 'pseudo-random'.  All deterministic generators are pseudo random. 
  200.  * This is opposed to true random generators based on some special
  201.  * physical device.
  202.  *
  203.  * The crypto generator is 'pseudo-random'.  There is no statistical 
  204.  * test, which runs in polynomial time, that can distinguish the crypto 
  205.  * generator from a truly random source.
  206.  *
  207.  * A final "truth in advertising" issue deals with how the magic numbers
  208.  * found in this library were generated.  Detains can be found in the
  209.  * various functions, while a overview can be found in the SOURCE FOR
  210.  * MAGIC NUMBERS section below.
  211.  *
  212.  ****
  213.  *
  214.  * ON THE GENERATORS:
  215.  *
  216.  * The additive 55 generator has a good period, and is fast.  It is
  217.  * reasonable as generators go, though there are better ones available.
  218.  * We use it in seeding the crypto generator as its period and
  219.  * other statistical properties are good enough for our purposes.
  220.  *
  221.  * This shuffle generator has a very good period, and is fast.  It is
  222.  * fairly good as generators go, and is better than the additive 55 
  223.  * generator.  Casual direct use of the shuffle generator may be 
  224.  * acceptable.  Because of this, the interface to the shuffle generator,
  225.  * but not the additive 55 generator, is advertised when this file is 
  226.  * loaded.
  227.  *
  228.  * The shuffle generator functions, shufrand() and rand() use the same
  229.  * seed and tables.  The shuffle generator shuffles the values produced
  230.  * by the additive 55 generator.  Calling or seeding the additive 55
  231.  * generator will affect the output of the shuffle generator.
  232.  *
  233.  * The crypto generator is the best generator in this package.  It
  234.  * produces a cryptographically strong pseudo-random bit sequence.
  235.  * Internally, a fixed number of bits are generated after each
  236.  * generator iteration.  Any unused bits are saved for the next call
  237.  * to the generator.  The crypto generator is not too slow, though
  238.  * seeding the generator from scratch is slow.  Shortcuts and
  239.  * pre-computer seeds have been provided for this reason.  Use of
  240.  * crypto should be more than acceptable for many applications.
  241.  *
  242.  * The crypto seed is in 4 parts, the additive 55 seed (lower 64
  243.  * bits of seed), the shuffle seed (all but the lower 64 bits of
  244.  * seed), and two lengths.  The two lengths specifies the minimum
  245.  * bit size of two primes used internal to the crypto generator.
  246.  * Not specifying the lengths, or using -1 will cause crypto to
  247.  * use the default minimum lengths of 248 and 264 bits, respectively.
  248.  *
  249.  * The random() function just another interface to the crypto
  250.  * generator.  Like rand(), random() provides an interval capability
  251.  * (closed or open) as well as a 64 bit default return value.
  252.  * The random() function as good as crypto, and produces numbers
  253.  * that are equally cryptographically strong.  One may use the
  254.  * seed functions srandom() or scryrand() for either the random()
  255.  * or cryrand() functions.
  256.  *
  257.  * The seed for all of the generators may be of any size.  Only the 
  258.  * lower 64 bits of seed affect the additive 55 generator.  Bits 
  259.  * beyond the lower 64 bits affect the shuffle generators.  Excessively
  260.  * large values of seed will result in increased memory usage as
  261.  * well as a larger seed time for the shuffle and crypto generators.
  262.  * See REGARDING SEEDS below, for more information.
  263.  *
  264.  * One may save and restore the state of all generators via the
  265.  * randstate() function.
  266.  *
  267.  ****
  268.  *
  269.  * REGARDING SEEDS:
  270.  *
  271.  * Because the generators are interrelated, seeding one generator
  272.  * will directly or indirectly affect the other generators.  Seeding
  273.  * the shuffle generator seeds the additive 55 generator.  Seeding
  274.  * the crypto generator seeds the shuffle generator.
  275.  *
  276.  * The seed of '0' implies that a generator should be seeded back
  277.  * to its initial default state.
  278.  *
  279.  * For the moment, seeds < -1 are reserved for future use.  The
  280.  * value of -1 is used as a special indicator to the fourth form 
  281.  * of scryrand(), and it not a real seed.
  282.  *
  283.  * A seed may be of any size.  The additive 55 generator uses only
  284.  * the lower 64 bits, while the shuffle generator uses bytes beyond
  285.  * the lower 64 bits.
  286.  *
  287.  * To help make the generator produced by seed S, significantly
  288.  * different from S+1, seeds are scrambled prior to use.  The
  289.  * function randreseed64() maps [0,2^64) into [0,2^64) in a 1-to-1
  290.  * and onto fashion.
  291.  *
  292.  * The purpose of the randreseed64() is not to add security.  It
  293.  * simply helps remove the human perception of the relationship
  294.  * between the seed and the production of the generator.
  295.  *
  296.  * The randreseed64() process does not reduce the security of the
  297.  * generators.  Every seed is converted into a different unique seed.
  298.  * No seed is ignored or favored.
  299.  *
  300.  * There is no limit on the size of a seed.  On the other hand,
  301.  * extremely large seeds require large tables and long seed times.
  302.  * Using a seed in the range of [2^64, 2^64 * 128!) should be
  303.  * sufficient for most purposes.  An easy way to stay within this
  304.  * range to to use seeds that are between 21 and 215 digits, or 64 to
  305.  * 780 bits long.
  306.  *
  307.  ****
  308.  *
  309.  * SOURCE OF MAGIC NUMBERS:
  310.  *
  311.  * Most of the magic constants used on this library ultimately are
  312.  * based on the Rand book of random numbers.  The Rand book contains
  313.  * 10^6 decimal digits, generated by a physical process.  This book,
  314.  * produced by the Rand corporation in the 1950's is considered
  315.  * a standard against which other generators may be measured.
  316.  *
  317.  * The Rand book of numbers was groups into groups of 20 digits.
  318.  * The first 55 groups < 2^64 were used to initialize add55_init_tbl.
  319.  * The size of 20 digits was used because 2^64 is 20 digits long.
  320.  * The restriction of < 2^64 was used to prevent modulus biasing.
  321.  * (see the note on  modulus biasing in rand()).
  322.  *
  323.  * The additive 55 generator during seeding is used 128 times to help
  324.  * remove the initial seed state from the initial values produced.
  325.  * The loop count of 128 was a power of 2 that permits each of the
  326.  * 55 table entries to be processed at least twice.
  327.  *
  328.  * The function, randreseed64(), uses 4 primes to scramble 64 bits
  329.  * into 64 bits.  These primes were also extracted from the Rand
  330.  * book of numbers.  See sshufrand() for details.
  331.  *
  332.  * The default shuffle table size of 128 entries is the power of 2
  333.  * that is longer than the 100 entries recommended by Knuth for
  334.  * the shuffle algorithm (see the text cited in shufrand()).
  335.  * We use a power of 2 shuffle table length so that the shuffle
  336.  * process can select a table entry from a new additive 55 value
  337.  * by extracting its top most bits.
  338.  *
  339.  * The quadratic residue search performed by cryres() starts at
  340.  * a value that is in the interval [2^sqrpow,n-3), where 2^sqrpow 
  341.  * is the first power of 2 > n^(3/4) and n = p*q.  We look at 1009
  342.  * random numbers in this interval for a quadratic residue.  If
  343.  * none are found, sqrpow is decremented by 1 if sqrpow > 2.
  344.  * In practice, decrementing sqrpow never happens.
  345.  *
  346.  * The use of n^(3/4) insures that the quadratic residue is
  347.  * large, but not too large.  We want to avoid residues that are
  348.  * near the square root of 'n', and are nearly 'n' itself (hence 
  349.  * the n-3 upper limit) as such residues are trivial or semi-trivial.
  350.  *
  351.  * The '1009' trials is simply an attempt to look for a while before
  352.  * picking a new range.  The number '1009' comes from the first 4
  353.  * digits of the rand book of numbers.
  354.  *
  355.  * Keeping sqrpow > 2 means that we do not look for quadratic
  356.  * residues that are below 4.  This is in keeping with the
  357.  * n-3 in the [2^sqrpow,n-3) interval.
  358.  *
  359.  * The final magic numbers: '248' and '264' are the exponents the
  360.  * largest powers of 2 that are < the two default Blum primes 'p'
  361.  * and 'q' used by the crypto generator.  The values of '248' and
  362.  * '264' implies that the product n=p*q > 2^512.  Each iteration
  363.  * of the crypto generator produces log2(log2(n=p*q)) random bits.
  364.  * The crypto generator is the most efficient when n is slightly >
  365.  * 2^(2^b).  The product n > 2^(2^9)) produces 9 bits as efficiently
  366.  * as possible under the crypto generator process.
  367.  *
  368.  * Not being able to factor 'n=p*q' into 'p' and 'q' does not directly
  369.  * improve the crypto generator.  On the other hand, it can't hurt.
  370.  * The two len values differ slightly to avoid factorization attacks 
  371.  * that work on numbers that are a perfect square, or where the two 
  372.  * primes are nearly the same.  I elected to have the sizes differ 
  373.  * by 3% of the product size.  The difference between '248' and 
  374.  * '264', is '16', which is ~3.125% of '512'.  Now 3% of '512' is 
  375.  * '~15.36', and the next largest whole number is '16'.
  376.  *
  377.  * The product n=p*q > 2^512 implies a product if at least 155 digits.
  378.  * A product of two primes that is at least 155 digits is slightly
  379.  * beyond Number Theory and computer power of Nov 1992, though this
  380.  * will likely change in the future.
  381.  *
  382.  * Again, the ability (or lack thereof) to factor 'n=p*q' does not
  383.  * directly relate to the strength of the crypto generator.  We 
  384.  * selected n=p*q > 2^512 mainly because '512 was a power of 2 and 
  385.  * only slightly because it is up in the range where it is difficult
  386.  * to factor.
  387.  *
  388.  ****
  389.  *
  390.  * FOR THE PARANOID:
  391.  *
  392.  * The truly paranoid might suggest that my claims in the MAGIC NUMBERS
  393.  * section are a lie intended to entrap people.  Well they are not, but
  394.  * you need not take my word for it.
  395.  *
  396.  * The random numbers from the Rand book of random numbers can be
  397.  * verified by anyone who obtains the book.  As these numbers were
  398.  * created before I (Landon Curt Noll) was born (you can look up
  399.  * my birth record if you want), I claim to have no possible influence
  400.  * on their generation.
  401.  *
  402.  * There is a very slight chance that the electronic copy of the
  403.  * Rand book that I was given access to differs from the printed text.
  404.  * I am willing to provide access to this electronic copy should
  405.  * anyone wants to compare it to the printed text.
  406.  *
  407.  * One might object to the complexity of the seed scramble/mapping
  408.  * via the randreseed64() function.  The randreseed64() function maps:
  409.  *
  410.  *    1 ==> 4967126403401436567
  411.  *
  412.  * calling srand(1) with the randreseed64() process would be the same
  413.  * as calling srand(4967126403401436567) without it.  No extra security
  414.  * is gained or reduced by using the randreseed64() process.  The meaning
  415.  * of seeds are exchanged, but not lost or favored (used by more than
  416.  * one input seed).
  417.  *
  418.  * One could take issue with my selection of the default sizes '248'
  419.  * and '264'.   As far as I know, 155 digits (512 bits) is beyond the
  420.  * state of the art of Number Theory and Computation as of 01 Sep 92.
  421.  * It will likely be true that 155 digit products of two primes could
  422.  * come within reach in the next few years, but so what?  If you are
  423.  * truly paranoid, why would you want to use the default seed, which
  424.  * is well known?
  425.  *
  426.  * The paranoid today might consider using the lengths of at least '345'
  427.  * and '325' will produce a product of two primes that is 202 digits.
  428.  * (the 2nd and 3rd args of scryrand > 345 & >325 respectively)  Factoring
  429.  * 200+ digit product of two primes is well beyond the current hopes of
  430.  * Number Theory and Computer power, though even this limit may be passed
  431.  * someday.
  432.  *
  433.  * If all the above fails to pacify the truly paranoid, then one may 
  434.  * select by some independent means, 2 Blum primes (primes mod 4 == 3, 
  435.  * p < q), and a quadratic residue if p*q.  Then by calling:
  436.  *
  437.  *    scryrand(-1, p, q, r)
  438.  *
  439.  * and then calling cryrand() or random(), one may bypass all magic
  440.  * numbers and use the pure generator.
  441.  *
  442.  * Note that randstate() may also be used by the truly paranoid.
  443.  * Even though it holds state for the other generators, their states
  444.  * are independent.
  445.  *
  446.  ****
  447.  *
  448.  * GOALS:
  449.  *
  450.  * The goals of this package are:
  451.  *
  452.  *    all magic numbers are explained
  453.  *
  454.  *        I distrust systems with constants (magic numbers) and tables
  455.  *        that have no justification (e.g., DES).  I believe that I have
  456.  *        done my best to justify all of the magic numbers used.
  457.  *
  458.  *     full documentation
  459.  *
  460.  *        You have this source file, plus background publications,
  461.  *        what more could you ask?
  462.  *
  463.  *    large selection of seeds
  464.  *
  465.  *        Seeds are not limited to a small number of bits.  A seed
  466.  *        may be of any size.
  467.  *
  468.  *    the strength of the generators may be tuned to meet the application need
  469.  *
  470.  *        By using the appropriate seed arguments, one may increase
  471.  *        the strength of the generator to suit the need of the
  472.  *        application.  One does not have just a few levels.
  473.  *
  474.  * This calc lib file is intended for demonstration purposes.  Writing
  475.  * a C program (with possible assembly or libmp assist) would produce
  476.  * a faster generator.
  477.  *
  478.  * Even though I have done my best to implement a good system, you still
  479.  * must use these routines your own risk.
  480.  *
  481.  * Share and enjoy!  :-)
  482.  */
  483.  
  484.  
  485. /*
  486.  * These constants are used by all of the generators in various direct and
  487.  * indirect forms.
  488.  */
  489. static cry_seed = 0;            /* master seed */
  490. static cry_mask = 0xffffffffffffffff;    /* 64 bit work mask */
  491.  
  492.  
  493. /*
  494.  * Initial magic values for the additive 55 generator - used by sa55rand()
  495.  *
  496.  * These values were generated from the Rand book of random numbers.
  497.  * In groups of 20 digits, we took the first 55 groups < 2^64.
  498.  */
  499. static mat add55_init_tbl[55] = {
  500.     10097325337652013586,    8422689531964509303,
  501.     9376707153831131165,    12807999708015736147,
  502.     12171768336606574717,    2051656926866574818,
  503.     3529647783580834282,    13746700781847540610,
  504.     17468509505804776974,    14385537637435099817,
  505.     14225685144642756788,    11100020401286074697,
  506.     7207317906119690446,    15474452669527079953,
  507.     16868487670307112059,    4493524947524633824,
  508.     13021248927856520106,    15956600001874392423,
  509.     1758753794041921585,    1540354560501451176,
  510.     5335129695612719255,    9973334408846123356,
  511.     2295368703230757546,    15020099946907494138,
  512.     10518216150184876938,    9188200973282539527,
  513.     4220863048338987374,    682273982071453295,
  514.     7706178130835869910,    4618975533122308420,
  515.     397583911260717646,    5686731560708285046,
  516.     10123916228549657560,    1304775865627110086,
  517.     15501295782182641134,    3061180729620744156,
  518.     6958929830512809719,    10850627469959910507,
  519.     13499063195307571839,    6410193623982098952,
  520.     4111084083850807341,    17719042079595449953,
  521.     5462692006544395659,    18288274374963224041,
  522.     8337656769629990836,    7477446061798548911,
  523.     9815931464890815877,    6913451974267278601,
  524.     11883095286301198901,    14974403441045516019,
  525.     14210337129134237821,    12883973436502761184,
  526.     4285013921797415077,    16435915296724552670,
  527.     3742838738308012451
  528. };
  529.  
  530.  
  531. /*
  532.  * additive 55 tables - used by a55rand() and sa55rand()
  533.  */
  534. static add55_j = 23;        /* the first walking table pointer */
  535. static add55_k = 54;        /* the second walking table pointer */
  536. static add55_seed64 = 0;    /* lower 64 bits of the reseeded seed */
  537. static mat add55_tbl[55];    /* additive 55 state table */
  538.  
  539.  
  540. /*
  541.  * cryobj - cryptographic pseudo-random state object
  542.  */
  543. obj cryobj {                            \
  544.     p,        /* first Blum prime (prime 3 mod 4) */        \
  545.     q,        /* second Blum prime (prime 3 mod 4) */        \
  546.     r,        /* quadratic residue of n=p*q */        \
  547.     exp,    /* used in computing crypto good bits */    \
  548.     left,    /* bits unused from the last cryrand() call */    \
  549.     bitcnt,    /* left contains bitcnt crypto good bits */    \
  550.     a55j,    /* 1st additive 55 table pointer */        \
  551.     a55k,    /* 2nd additive 55 table pointer */        \
  552.     seed,    /* last seed set by sa55rand() or 0 */        \
  553.     shufy,    /* Y (previous a55rand output for shuffle) */    \
  554.     shufsz,    /* size of the shuffle table */            \
  555.     shuftbl,    /* a matrix of shufsz entries */        \
  556.     a55tbl    /* additive 55 generator state table */        \
  557. }
  558.  
  559.  
  560. /*
  561.  * initial cryptographic pseudo-random values - used by scryrand()
  562.  *
  563.  * These values are what the crypto generator is initialized with
  564.  * with this library first read.  These values may be reproduced the
  565.  * hard way by calling scryrand(0,248,264) or scryrand(0,-1,-1).
  566.  *
  567.  * We will build up these values a piece at a time to avoid long lines
  568.  * that are difficult to send via Email.
  569.  */
  570. /* p, first Blum prime */
  571. static cryrand_init_p = 0x1aa9e726a735044;
  572. cryrand_init_p <<= 200;
  573. cryrand_init_p |= 0x73b7457c5297122310880fcbfa8d4e38380a00396d533300bb;
  574. /* q, second Blum prime */
  575. static cryrand_init_q = 0xa62ee0481aa12059c3;
  576. cryrand_init_q <<= 200;
  577. cryrand_init_q |= 0x79ef44e72ff58ea70cacabbe9d264a0b16db72117d96f77e17;
  578. /* quadratic residue of n=p*q */
  579. static cryrand_init_r = 0x3d214853f9a5bb4b12f467c9052129a9;
  580. cryrand_init_r <<= 200;
  581. cryrand_init_r |= 0xd215cc6b3c2eae8c7090591b16d8044a886b3c6a58759b1a07;
  582. cryrand_init_r <<= 200;
  583. cryrand_init_r |= 0x2b50a914b42e1b6f9703be86742837c4bc637804c2dc668c5b;
  584.  
  585. /*
  586.  * cryptographic pseudo-random values - used by cryrand() and scryrand()
  587.  */
  588. /* p, first Blum prime */
  589. static cryrand_p = cryrand_init_p;
  590. /* q, second Blum prime */
  591. static cryrand_q = cryrand_init_q;
  592. /* n = p*q */
  593. static cryrand_n = cryrand_p*cryrand_q;
  594. /* quad residue of n */
  595. static cryrand_r = cryrand_init_r;
  596. /* this cryrand() running exp used in computing crypto good bits */
  597. static cryrand_exp = cryrand_r;
  598. /* good crypto bits unused from the last cryrand() call */
  599. static cryrand_left = 0;
  600. /* the value cryrand_left contains cryrand_bitcnt crypto good bits */
  601. static cryrand_bitcnt = 0;
  602.  
  603.  
  604. /*
  605.  * shufrand - shuffle generator constants
  606.  */
  607. static shuf_size = 128;            /* entries in shuffle table */
  608. static shuf_shift = (64-highbit(shuf_size));    /* shift a55 value to get tbl indx */
  609. static shuf_y;                /* Y value (previous output) */
  610. static mat shuf_tbl[shuf_size];        /* shuffle state table */
  611.  
  612.  
  613. /*
  614.  * products of consecutive primes - used by nxtprime()
  615.  *
  616.  * We compute these products now to avoid recalculating them on each call.
  617.  * These values help weed out numbers that have a prime factor < 1000.
  618.  */
  619. static nxtprime_pfact10 = pfact(10);
  620. static nxtprime_pfact100 = pfact(100)/nxtprime_pfact10;
  621. static nxtprime_pfact1000 = pfact(1000)/nxtprime_pfact100;
  622.  
  623.  
  624. /*
  625.  * a55rand - additive 55 pseudo-random number generator
  626.  *
  627.  * returns:
  628.  *    A number in the half open interval [0,2^64)
  629.  *
  630.  * This function implements the additive 55 pseudo-random number generator.
  631.  *
  632.  * This is a generator based on the additive 55 generator as described in
  633.  * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  634.  * vol 2, 2nd edition (1981), Section 3.2.2, page 27, Algorithm A.
  635.  *
  636.  * This function is called from the shuffle generator function shufrand().
  637.  *
  638.  * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  639.  *       generate some internal values.
  640.  *
  641.  * NOTE: If you are looking for a fast generator and do not need a crypto
  642.  *      strong generator, you should not use this generator.  Use of
  643.  *     the shuffle generator functions shufrand() and rand() should
  644.  *     be considered instead.
  645.  */
  646. define
  647. a55rand()
  648. {
  649.     local ret;            /* the pseudo-random number to return */
  650.  
  651.     /* generate the next value using the additive 55 generator method */
  652.     ret = add55_tbl[add55_k] + add55_tbl[add55_j];
  653.     ret &= cry_mask;
  654.     add55_tbl[add55_k] = ret;
  655.  
  656.     /* post-process out data with the seed */
  657.     ret = xor(ret, add55_seed64);
  658.  
  659.     /* step the pointers */
  660.     --add55_j;
  661.     if (add55_j < 0) {
  662.     add55_j = 54;
  663.     }
  664.     --add55_k;
  665.     if (add55_k < 0) {
  666.     add55_k = 54;
  667.     }
  668.  
  669.     /* return the new pseudo-random number */
  670.     return(ret);
  671. }
  672.  
  673.  
  674. /*
  675.  * sa55rand - initialize the additive 55 pseudo-random generator
  676.  *
  677.  * given:
  678.  *    seed
  679.  *
  680.  * returns:
  681.  *    old_seed
  682.  *
  683.  * This function seeds the additive 55 pseudo-random generator.
  684.  *
  685.  * This is a generator based on the additive 55 generator as described in
  686.  * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  687.  * vol 2, 2nd edition (1981), Section 3.2.2, page 27, Algorithm A.
  688.  *
  689.  * Unlike Knuth's description, we will let a seed post process our data.
  690.  *
  691.  * We do not apply the seed processing to the additive 55 table
  692.  * data as this would disturb its pseudo-random generator properties.
  693.  * Instead, we xor the output with the low 64 bits of seed.
  694.  *
  695.  * If seed == 0:
  696.  *
  697.  *    This function produces values in exactly the same way
  698.  *    described by Knuth.
  699.  *
  700.  * else:
  701.  *
  702.  *    Each value produced is xor-ed by a 64 bit value.  This value
  703.  *    is the result of randreseed64(rand), which produces a 64
  704.  *    bit value.
  705.  *
  706.  * Anyone comfortable with seed == 0 should also be comfortable with
  707.  * non-zero seeds.  A non-zero seeded sequence will produce a values
  708.  * that have the exact same pseudo-random properties as the algorithm
  709.  * described by Knuth.  I.e., the sequence, while different, is as good
  710.  * (or bad) as the sequence produced by a seed of 0.
  711.  *
  712.  * This function updates both the cry_seed and a55_seed64 global values.
  713.  *
  714.  * This function is called from the shuffle generator seed function sshufrand().
  715.  *
  716.  * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  717.  *       generate some internal values.
  718.  *
  719.  * NOTE: If you are looking for a fast generator and do not need a crypto
  720.  *      strong generator, you should not use this generator.  Use of the
  721.  *     shuffle generator seed functions sshufrand() and srand() should
  722.  *     be considered instead.
  723.  */
  724. define
  725. sa55rand(seed)
  726. {
  727.     local oldseed;        /* previous seed */
  728.     local junk;            /* discards the first few numbers */
  729.     local j;
  730.  
  731.     /* firewall */
  732.     if (!isint(seed)) {
  733.     quit "bad arg: arg must be an integer";
  734.     }
  735.     if (seed < 0) {
  736.     quit "bad arg: seed < 0 is reserved for future use";
  737.     }
  738.  
  739.     /* misc table setup */
  740.     oldseed = cry_seed;                /* remember the previous seed */
  741.     cry_seed = seed;                /* save the new seed */
  742.     add55_tbl = add55_init_tbl;    /* reload the table */
  743.     add55_j = 23;               /* reset first walking table pointer */
  744.     add55_k = 54;               /* reset second walking table pointer */
  745.  
  746.     /* obtain our 64 bit xor seed */
  747.     add55_seed64 = randreseed64(seed);
  748.  
  749.     /* spin the pseudo-random number generator a while */
  750.     for (j=0; j < 128; ++j) {
  751.     junk = a55rand();
  752.     }
  753.  
  754.     /* return the old seed */
  755.     return(oldseed);
  756. }
  757.  
  758.  
  759. /*
  760.  * shufrand - implement the shuffle pseudo-random number generator
  761.  *
  762.  * returns:
  763.  *    A number in the half open interval [0,2^64)
  764.  *
  765.  * This function implements the shuffle number generator.
  766.  *
  767.  * This is a generator based on the shuffle generator as described in
  768.  * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  769.  * vol 2, 2nd edition (1981), Section 3.2.2, page 32, Algorithm B.
  770.  *
  771.  * The function rand() calls this function.
  772.  *
  773.  * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  774.  *       generate some internal values.
  775.  *
  776.  * NOTE: If you do not need a crypto strong pseudo-random generator
  777.  *     this function may very well serve your needs.
  778.  */
  779. define
  780. shufrand()
  781. {
  782.     local j;        /* table index to replace */
  783.  
  784.     /*
  785.      * obtain a new random value
  786.      * determine the table entry to shuffle
  787.      * shuffle out the value we will return
  788.      */
  789.     shuf_y = shuf_tbl[j = (shuf_y >> shuf_shift)];
  790.  
  791.     /* shuffle in the new random value */
  792.     shuf_tbl[j] = a55rand();
  793.  
  794.     /* return the shuffled out value */
  795.     return (shuf_y);
  796. }
  797.  
  798.  
  799. /*
  800.  * sshufrand - seed the shuffle pseudo-random generator
  801.  *
  802.  * given:
  803.  *    a seed
  804.  *
  805.  * returns:
  806.  *    the previous seed
  807.  *
  808.  * This function implements the shuffle number generator.
  809.  *
  810.  * This is a generator based on the shuffle generator as described in
  811.  * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  812.  * vol 2, 2nd edition (1981), Section 3.2.2, page 32, Algorithm B.
  813.  *
  814.  * The low 64 bits of seed are used by the additive 55 generator.
  815.  * See the sa55rand() function for details.  The remaining bits of seed
  816.  * are used to perform an initial shuffle on the shuffle state table.
  817.  * The size of the seed also determines the size of the shuffle table.
  818.  *
  819.  * The shuffle table size is always a power of 2, and is at least 128
  820.  * entries long.  Let the table size be:
  821.  *
  822.  *    shuf_size = 2^shuf_pow
  823.  *
  824.  * The number of ways one could shuffle that table is:
  825.  *
  826.  *    (2^shuf_pow)!
  827.  *
  828.  * We select the smallest 'shuf_pow' (and thus the size of the shuffle table)
  829.  * such that the following are true:
  830.  *
  831.  *    (2^shuf_pow)! >= (seed / 2^64)    and    2^shuf_pow >= 128
  832.  *
  833.  * Given that we now have the table size of 'shuf_size', we must go about
  834.  * loading the table and shuffling it.
  835.  *
  836.  * Loading is easy, we will generate random values via the additive 55
  837.  * generator (a55rand()) and load them into successive entries.
  838.  *
  839.  * We enumerate the (2^shuf_pow)! values via:
  840.  *
  841.  *    shuf_seed = 2*(U[2] + 3*(U[3] + 4*(U[4] + ...
  842.  *              + (U[shuf_pow-1]*(shuf_pow-1)) ... )))
  843.  *    0 <= U[j] < j
  844.  *
  845.  * We swap the swap table entries shuf_tbl[U[j]] & shuf_tbl[j-1] for all
  846.  * 1 < j < shuf_pow.
  847.  *
  848.  * We will convert 'seed / 2^64' into shuf_seed, by applying the 64 bit
  849.  * scramble function on 64 bit chunks of 'seed / 2^64'.
  850.  *
  851.  * The function srand() calls this function.
  852.  *
  853.  * There is no limit on the size of a seed.  On the other hand,
  854.  * extremely large seeds require large tables and long seed times.
  855.  * Using a seed in the range of [2^64, 2^64 * 128!) should be
  856.  * sufficient for most purposes.  An easy way to stay within this
  857.  * range to to use seeds that are between 21 and 215 digits long, or
  858.  * 64 to 780 bits long.
  859.  *
  860.  * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  861.  *       generate some internal values.
  862.  *
  863.  * NOTE: If you do not need a crypto strong pseudo-random generator
  864.  *     this function may very well serve your needs.
  865.  */
  866. define
  867. sshufrand(seed)
  868. {
  869.     local shuf_pow;        /* power of two - log2(shuf_size) */
  870.     local shuf_seed;        /* seed bits beyond low 64 bits */
  871.     local oldseed;        /* previous seed */
  872.     local shift;        /* shift factor to access 64 bit chunks */
  873.     local swap_indx;        /* what to swap shuf_tbl[0] with */
  874.     local rval;            /* random value form additive 55 generator */
  875.     local j;
  876.  
  877.     /* firewall */
  878.     if (!isint(seed)) {
  879.     quit "bad arg: seed must be an integer";
  880.     }
  881.     if (seed < 0) {
  882.     quit "bad arg: seed < 0 is reserved for future use";
  883.     }
  884.  
  885.     /*
  886.      * seed the additive 55 generator
  887.      */
  888.     oldseed = sa55rand(seed);
  889.  
  890.     /*
  891.      * form the shuffle table size and constants
  892.      */
  893.     shuf_seed = seed >> 64;
  894.     for (shuf_pow = 7; shuf_seed > (j=fact(1<<(shuf_pow))) && shuf_pow < 64; \
  895.      ++shuf_pow) {
  896.     }
  897.     shuf_size = (1 << shuf_pow);
  898.     shuf_shift = 64 - shuf_pow;
  899.     /* reallocate the shuffle table */
  900.     mat shuf_tbl[shuf_size];
  901.  
  902.     /*
  903.      * scramble the seed above the low 64 bits
  904.      */
  905.     if (shuf_seed > 0) {
  906.     j = 0;
  907.     for (shift=0; shift < highbit(shuf_seed)+1; shift += 64) {
  908.         j |= (randreseed64(shuf_seed >> shift) << shift);
  909.     }
  910.     shuf_seed = j;
  911.     }
  912.  
  913.     /*
  914.      * load the shuffle table
  915.      */
  916.     for (j=0; j < shuf_size; ++j) {
  917.     shuf_tbl[j] = a55rand();
  918.     }
  919.     shuf_y = a55rand();        /* get the next Y value */
  920.  
  921.     /*
  922.      * We will shuffle based the process outlined in:
  923.      *
  924.      * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  925.      * vol 2, 2nd edition (1981), Section 3.4.2, page 139, Algorithm P.
  926.      *
  927.      * Here, we will let j run over the range [0,shuf_size) instead of
  928.      * [shuf_size,0) as outlined in algorithm P.  We will also generate
  929.      * U values from shuf_seed.
  930.      */
  931.     j = 0;
  932.     while (shuf_seed > 0 && ++j < shuf_size) {
  933.  
  934.     /* determine what index we will swap with the '0' index */
  935.     quomod(shuf_seed, (j+1), shuf_seed, swap_indx);
  936.  
  937.     /* swap table entries, if needed */
  938.     if (swap_indx != j) {
  939.         swap(shuf_tbl[j], shuf_tbl[swap_indx]);
  940.     }
  941.     }
  942.  
  943.     /*
  944.      * run the generator for twice the table size
  945.      */
  946.     for (j=0; j < shuf_size*2; ++j) {
  947.     rval = shufrand();
  948.     }
  949.  
  950.     /* return the old seed */
  951.     return (oldseed);
  952. }
  953.  
  954.  
  955. /*
  956.  * rand - generate a pseudo-random value over a given range via additive 55
  957.  *
  958.  * usage:
  959.  *    rand()         - generate a pseudo-random integer >=0 and < 2^64
  960.  *    rand(a)     - generate a pseudo-random integer >=0 and < a
  961.  *    rand(a,b)    - generate a pseudo-random integer >=a and <= b
  962.  *
  963.  * returns:
  964.  *    a large pseudo-random integer over a give range (see usage)
  965.  *
  966.  * When no arguments are given, a pseudo-random number in the half open
  967.  * interval [0,2^64) is produced.  This form is identical to calling 
  968.  * shufrand().
  969.  *
  970.  * When 1 argument is given, a pseudo-random number in the half open interval
  971.  * [0,a) is produced.
  972.  *
  973.  * When 2 arguments are given, a pseudo-random number in the closed interval
  974.  * [a,b] is produced.
  975.  *
  976.  * The input values a and b, if given, must be integers.
  977.  *
  978.  * This generator is simply a different interface to the shuffle generator.
  979.  * calling shufrand(), or seeding via sshufrand() will affect the output
  980.  * of this function.
  981.  *
  982.  * NOTE: Unlike cryrand(), this function does not preserve unused bits for
  983.  *     use by the next function call.
  984.  *
  985.  * NOTE: The Un*x rand() function returns only 16 bit or 31 bits, while we
  986.  *     return a number of any given size (default is 64 bits).
  987.  *
  988.  * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  989.  *       generate some internal values.
  990.  *
  991.  * NOTE: If you do not need a crypto strong pseudo-random generator
  992.  *     this function may very well serve your needs.
  993.  */
  994. define
  995. rand(a,b)
  996. {
  997.     local range;        /* we must generate [0,range) first */
  998.     local offset;        /* what to add to get a adjusted range */
  999.     local ret;            /* pseudo-random value */
  1000.     local fullwords;        /* number of full 64 bit chunks in ret */
  1001.     local finalmask;        /* mask of bits in final chunk of range */
  1002.     local j;
  1003.  
  1004.     /*
  1005.      * setup and special cases
  1006.      */
  1007.     /* deal with the rand() case */
  1008.     if (isnull(a) && isnull(b)) {
  1009.     /* no args means same range as additive 55 generator */
  1010.     return(a55rand());
  1011.     }
  1012.     /* firewall - args, if given must be in integers */
  1013.     if (!isint(a) || (!isnull(b) && !isint(b))) {
  1014.     quit "bad args: args, if given, must be integers";
  1015.     }
  1016.     /* convert rand(x) into rand(0,x-1) */
  1017.     if (isnull(b)) {
  1018.     /* convert call into a closed interval */
  1019.     b = a-1;
  1020.     a = 0;
  1021.     /* firewall - rand(0) should act like rand(0,0) */
  1022.     if (b == -1) {
  1023.         return(0);
  1024.     }
  1025.     }
  1026.     /* determine the range and offset */
  1027.     if (a >= b) {
  1028.     /* deal with the case of rand(a,a) */
  1029.     if (a == b) {
  1030.         /* not very random, but it is true! */
  1031.         return(a);
  1032.     }
  1033.     range = a-b+1;
  1034.     offset = b;
  1035.     } else {
  1036.     /* convert rand(a,b), where a < b into rand(b,a) */
  1037.     range = b-a+1;
  1038.     offset = a;
  1039.     }
  1040.     /*
  1041.      * At this point, we seek a pseudo-random number [0,range) to which
  1042.      * we will add offset to produce a number [offset,range+offset).
  1043.      */
  1044.     fullwords = highbit(range-1)//64;
  1045.     finalmask = (1 << (1+(highbit(range-1)%64)))-1;
  1046.  
  1047.     /*
  1048.      * loop until we get a value that is in range
  1049.      *
  1050.      * A note in modulus biasing:
  1051.      *
  1052.      * We will not fall into the trap of thinking that we can simply take
  1053.      * a value mod 'range'.  Consider the case where 'range' is '80'
  1054.      * and we are given pseudo-random numbers [0,100).  If we took them
  1055.      * mod 80, then the numbers [0,20) would be produced more frequently
  1056.      * because the numbers [81,100) mod 80 wrap back into [0,20).
  1057.      */
  1058.     do {
  1059.     /* load up all lower full 64 bit chunks with pseudo-random bits */
  1060.     ret = 0;
  1061.     for (j=0; j < fullwords; ++j) {
  1062.         ret = (ret << 64) + shufrand();
  1063.     }
  1064.  
  1065.     /* load the highest chunk */
  1066.     ret <<= (highbit(finalmask)+1);
  1067.     ret |= (shufrand() >> (64-highbit(finalmask)-1));
  1068.     } while (ret >= range);
  1069.  
  1070.     /*
  1071.      * return the adjusted range value
  1072.      */
  1073.     return(ret+offset);
  1074. }
  1075.  
  1076.  
  1077. /*
  1078.  * srand - seed the pseudo-random additive 55 generator
  1079.  *
  1080.  * input:
  1081.  *    seed
  1082.  *
  1083.  * returns:
  1084.  *    old_seed
  1085.  *
  1086.  * This function actually seeds the shuffle generator (and indirectly
  1087.  * the additive 55 generator used by rand() and a55rand().
  1088.  *
  1089.  * See sshufrand() and sa55rand() for information about a seed.
  1090.  *
  1091.  * There is no limit on the size of a seed.  On the other hand,
  1092.  * extremely large seeds require large tables and long seed times.
  1093.  * Using a seed in the range of [2^64, 2^64 * 128!) should be
  1094.  * sufficient for most purposes.  An easy way to stay within this
  1095.  * range to to use seeds that are between 21 and 215 digits long, or
  1096.  * 64 to 780 bits long.
  1097.  *
  1098.  * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  1099.  *       generate some internal values.
  1100.  *
  1101.  * NOTE: If you do not need a crypto strong pseudo-random generator
  1102.  *     this function may very well serve your needs.
  1103.  */
  1104. define
  1105. srand(seed)
  1106. {
  1107.     if (!isint(seed)) {
  1108.     quit "bad arg: seed must be an integer";
  1109.     }
  1110.     if (seed < 0) {
  1111.     quit "bad arg: seed < 0 is reserved for future use";
  1112.     }
  1113.     return(sshufrand(seed));
  1114. }
  1115.  
  1116.  
  1117. /*
  1118.  * cryrand - cryptographically strong pseudo-random number generator
  1119.  *
  1120.  * usage:
  1121.  *    cryrand(len)
  1122.  *
  1123.  * given:
  1124.  *    len        number of pseudo-random bits to generate
  1125.  *
  1126.  * returns:
  1127.  *    a cryptographically strong pseudo-random number of len bits
  1128.  *
  1129.  * Internally, bits are produced log2(log2(n=p*q)) at a time.  If a
  1130.  * call to this function does not exhaust all of the collected bits,
  1131.  * the unused bits will be saved away and used at a later call.
  1132.  * Setting the seed via scryrand() or srandom() will clear out all
  1133.  * unused bits.  Thus:
  1134.  *
  1135.  *    scryrand(0);            <-- restore generator to initial state
  1136.  *    cryrand(16);            <-- 16 bits
  1137.  *
  1138.  * will produce the same value as:
  1139.  *
  1140.  *    scryrand(0);            <-- restore generator to initial state
  1141.  *    cryrand(4)<<12 | cryrand(12);    <-- 4+12 = 16 bits
  1142.  *
  1143.  * and will produce the same value as:
  1144.  *
  1145.  *    scryrand(0);            <-- restore generator to initial state
  1146.  *    cryrand(3)<<13 | cryrand(7)<<6 | cryrand(6);    <-- 3+7+6 = 16 bits
  1147.  *
  1148.  * The crypto generator is not as fast as most generators, though it is not 
  1149.  * painfully slow either.
  1150.  *
  1151.  * NOTE: This function is the Blum cryptographically strong
  1152.  *     pseudo-random number generator!
  1153.  */
  1154. define
  1155. cryrand(len)
  1156. {
  1157.     local goodbits;    /* the number of good bits generated each pass */
  1158.     local goodmask;    /* mask for the low order good bits */
  1159.     local randval;    /* pseudo-random value being generated */
  1160.  
  1161.     /*
  1162.      * firewall
  1163.      */
  1164.     if (!isint(len) || len < 1) {
  1165.     quit "bad arg: len must be an integer > 0";
  1166.     }
  1167.  
  1168.     /*
  1169.      * Determine how many bits may be generated each pass.
  1170.      *
  1171.      * The result by Alexi et. al., says that the log2(log2(n=p*q))
  1172.      * least significant bits are secure, where log2(x) is log base 2.
  1173.      */
  1174.     goodbits = highbit(highbit(cryrand_n));
  1175.     goodmask = (1 << goodbits)-1;
  1176.  
  1177.     /*
  1178.      * If we have bits left over from the previous call, collect
  1179.      * them now.
  1180.      */
  1181.     if (cryrand_bitcnt > 0) {
  1182.  
  1183.     /* case where the left over bits are enough for this call */
  1184.     if (len <= cryrand_bitcnt) {
  1185.  
  1186.         /* we need only len bits */
  1187.         randval = (cryrand_left >> (cryrand_bitcnt-len));
  1188.  
  1189.         /* save the unused bits for later use */
  1190.         cryrand_left &= ((1 << (cryrand_bitcnt-len))-1);
  1191.  
  1192.         /* save away the number of bits that we will not use */
  1193.         cryrand_bitcnt -= len;
  1194.  
  1195.         /* return our complete result */
  1196.         return(randval);
  1197.  
  1198.     /* case where we need more than just the left over bits */
  1199.     } else {
  1200.  
  1201.         /* clear out the number of left over bits */
  1202.         len -= cryrand_bitcnt;
  1203.         cryrand_bitcnt = 0;
  1204.  
  1205.         /* collect all of the left over bits for now */
  1206.         randval = cryrand_left;
  1207.     }
  1208.  
  1209.     /* case where we have no previously left over bits */
  1210.     } else {
  1211.     randval = 0;
  1212.     }
  1213.  
  1214.     /*
  1215.      * Pump out len cryptographically strong pseudo-random bits,
  1216.      * 'goodbits' at a time using Blum's process.
  1217.      */
  1218.     while (len >= goodbits) {
  1219.  
  1220.     /* generate the bits */
  1221.     cryrand_exp = (cryrand_exp^2) % cryrand_n;
  1222.     randval <<= goodbits;
  1223.     randval |= (cryrand_exp & goodmask);
  1224.  
  1225.     /* reduce the need count */
  1226.     len -= goodbits;
  1227.     }
  1228.  
  1229.     /* if needed, save the unused bits for later use */
  1230.     if (len > 0) {
  1231.  
  1232.     /* generate the bits */
  1233.     cryrand_exp = (cryrand_exp^2) % cryrand_n;
  1234.     randval <<= len;
  1235.     randval |= ((cryrand_exp&goodmask) >> (goodbits-len));
  1236.  
  1237.     /* save away the number of bits that we will not use */
  1238.     cryrand_left = cryrand_exp & ((1 << (goodbits-len))-1);
  1239.     cryrand_bitcnt = goodbits-len;
  1240.     }
  1241.  
  1242.     /*
  1243.      * return our pseudo-random bits
  1244.      */
  1245.      return(randval);
  1246. }
  1247.  
  1248.  
  1249. /*
  1250.  * scryrand - seed the cryptographically strong pseudo-random number generator
  1251.  *
  1252.  * usage:
  1253.  *    scryrand(seed)
  1254.  *    scryrand()
  1255.  *    scryrand(seed,len1,len2)
  1256.  *    scryrand(seed,ip,iq,ir)
  1257.  *
  1258.  * input:
  1259.  *    [seed        pseudo-random seed
  1260.  *    [len1 len2]    minimum bit length of the Blum primes 'p' and 'q'
  1261.  *            -1 => default lengths
  1262.  *    [ip iq ir]    Initial search values for Blum primes 'p', 'q' and 
  1263.  *            a quadratic residue 'r'
  1264.  *
  1265.  * returns:
  1266.  *    the previous seed
  1267.  *
  1268.  *
  1269.  * This function will seed and setup the generator needed to produce
  1270.  * cryptographically strong pseudo-random numbers.  See the function
  1271.  * a55rand() and sshufrand() for information about how 'seed' works.
  1272.  *
  1273.  * The first form of this function are fairly fast if the seed is not
  1274.  * excessively large.  The second form is also fairly fast if the internal
  1275.  * primes are not too large.  The third form, can take a long time to call.
  1276.  * (see below)   The fourth form, if the 'seed' arg is not -1, can take 
  1277.  * as long as the third form to call.  If the fourth form is called with
  1278.  * a 'seed' arg of -1, then it is fairly fast.
  1279.  *
  1280.  * Calling scryrand() with 1 or 3 args (first and third forms), or
  1281.  * calling srandom(), or calling scryrand() with 4 args with the first
  1282.  * arg >0, will leave the shuffle generator in a seeded state as if 
  1283.  * sshufrand(seed) has been called.  
  1284.  *
  1285.  * Calling scryrand() with no args will not seed the shuffle generator, 
  1286.  * before or afterwards, however the shuffle generator will have been 
  1287.  * changed as a side effect of that call.
  1288.  *
  1289.  * Calling scryrand() with 4 args where the first arg is 0 or '-1'
  1290.  * will not change the other generators.
  1291.  *
  1292.  *
  1293.  * First form of call:  scryrand(seed)
  1294.  *
  1295.  * The first form of this function will seed the shuffle generator
  1296.  * (via srand).  The default precomputed constants will be used.
  1297.  *
  1298.  *
  1299.  * Second form of call:  scryrand()
  1300.  *
  1301.  * Only a new quadratic residue of n=p*q is recomputed.  The previous prime
  1302.  * values are kept.
  1303.  *
  1304.  * Unlike the first and second forms of this function, the shuffle
  1305.  * generator function is not seeded before or after the call.  The 
  1306.  * current state is used to generate a new quadratic residue of n=p*q.
  1307.  *
  1308.  *
  1309.  * Third form of call:  scryrand(seed,len1,len2)
  1310.  *
  1311.  * In the third form, 'len1' and 'len2' guide this function in selecting
  1312.  * internally used prime numbers.  The larger the lengths, the longer
  1313.  * the time this function will take.  The impact on execution time of
  1314.  * cryrand() and random() may also be noticed, but not as much.
  1315.  *
  1316.  * If a length is '-1', then the default lengths (248 for len1, and 264
  1317.  * for len2) are used.  The call scryrand(0,-1,-1) recreates the initial
  1318.  * crypto state the slow and hard way.  (use scryrand(0) or srandom(0))
  1319.  *
  1320.  * This function can take a long time to call given reasonable values
  1321.  * of len1 and len2.  On a Pyramid R3000, the time to seed was:
  1322.  *
  1323.  *    Approx value    digits   seed time
  1324.  *      of len1+len2   in n=p*q       in sec
  1325.  *    ------------   --------       ------
  1326.  *          8           3         0.53
  1327.  *         16           5         0.54
  1328.  *         32          10         0.79
  1329.  *         64          20         1.17
  1330.  *        128          39         2.89
  1331.  *        200          61         4.68
  1332.  *        256          78         7.49
  1333.  *        322         100        12.47
  1334.  *        464         140        35.56
  1335.  *        512         155        53.57
  1336.  *        664         200        83.97
  1337.  *        830         250       122.93
  1338.  *        996         300       242.49
  1339.  *       1024         309       295.66
  1340.  *       1328         400       663.44
  1341.  *       1586         478      2002.10
  1342.  *       1660         500      1643.45  (Faster mult/square methods kick in
  1343.  *       1992         600      2885.81   in certain cases. Type  help config
  1344.  *       2048         617      1578.06   in calc for more details.)
  1345.  *
  1346.  *     NOTE: The small lengths above are given for comparison 
  1347.  *           purposes and are NOT recommended for actual use.
  1348.  *
  1349.  *     NOTE: Generating crypto pseudo-random numbers is MUCH 
  1350.  *           faster than seeding a crypto generator.
  1351.  *
  1352.  *     NOTE: This calc lib file is intended for demonstration 
  1353.  *           purposes.  Writing a C program (with possible assembly 
  1354.  *           or libmp assist) would produce a faster generator.
  1355.  *
  1356.  *
  1357.  * Fourth form of call:  scryrand(seed,ip,iq,ir)
  1358.  *
  1359.  * In the fourth form, 'ip', 'iq' and 'ir' serve as initial search
  1360.  * values for the two Blum primes 'p' and 'q' and an associated
  1361.  * quadratic residue 'r' respectively.  Unlike the 3rd form, where 
  1362.  * lengths are given, the fourth form allows one to specify minimum 
  1363.  * search values.
  1364.  *
  1365.  * The 'seed' value is interpreted as follows:
  1366.  *
  1367.  *   If seed > 0:
  1368.  *
  1369.  *    Seed and use the shuffle generator to generate 3 jump values 
  1370.  *    that are in the range '[0,ip)', '[0,iq)' and '[0,ir)' respectively.
  1371.  *    Start searching for legal 'p', 'q' and 'r' values by adding 
  1372.  *    the jump values to their respective argument values.
  1373.  *
  1374.  *   If seed == 0:
  1375.  *
  1376.  *    Start searching for legal 'p', 'q' and 'r' values from
  1377.  *    'ip', 'iq' and 'ir' respectively.
  1378.  *
  1379.  *    This form does not change/seed the other generators.
  1380.  *
  1381.  *   If seed == -1:
  1382.  *
  1383.  *    Let 'p' == 'ip', 'q' == 'iq' and 'r' == 'ir'.  Do not check 
  1384.  *    if the value given are legal Blum primes or an associated 
  1385.  *    quadratic residue respectively.
  1386.  *
  1387.  *    This form does not change/seed the other generators.
  1388.  *
  1389.  *    WARNING: No checks are performed on the args passed.
  1390.  *         Passing improper values will likely produce
  1391.  *         poor results, or worse!
  1392.  *
  1393.  *
  1394.  * It should be noted that calling scryrand() while using the default
  1395.  * primes took only 0.04 seconds.  Calling scryrand(0,-1,-1) took
  1396.  * 47.19 seconds.
  1397.  *
  1398.  * The paranoid, when giving explicit lengths, should keep in mind that
  1399.  * len1 and len2 are the largest powers of 2 that are less than the two 
  1400.  * probable primes ('p' and 'q').  These two primes  will be used 
  1401.  * internally to cryrand().  For simplicity, we refer to len1 and len2
  1402.  * as bit lengths, even though they are actually 1 less then the
  1403.  * minimum possible prime length.
  1404.  *
  1405.  * The actual lengths may exceed the lengths by slightly more than 3%.
  1406.  * Furthermore, part of the strength of this generator rests on the
  1407.  * difficultly to factor 'p*q'.  Thus one should select 'len1' and 'len2'
  1408.  * (from which 'p' and 'q' are selected) such that factoring a 'len1+len2'
  1409.  * bit number is difficult.
  1410.  *
  1411.  * Not being able to factor 'n=p*q' into 'p' and 'q' does not directly
  1412.  * improve the crypto generator.  On the other hand, it can't hurt.
  1413.  *
  1414.  * There is no limit on the size of a seed.  On the other hand,
  1415.  * extremely large seeds require large tables and long seed times.
  1416.  * Using a seed in the range of [2^64, 2^64 * 128!) should be
  1417.  * sufficient for most purposes.  An easy way to stay within this
  1418.  * range to to use seeds that are between 21 and 215 digits long, or
  1419.  * 64 to 780 bits long.
  1420.  *
  1421.  * NOTE: This function will clear any internally buffer bits.  See
  1422.  *     cryrand() for details.
  1423.  *
  1424.  * NOTE: This function seeds the Blum cryptographically strong
  1425.  *     pseudo-random number generator.
  1426.  */
  1427. define
  1428. scryrand(seed,len1,len2,arg4)
  1429. {
  1430.     local rval;        /* a temporary pseudo-random value */
  1431.     local oldseed;    /* the previous seed */
  1432.     local newres;    /* the new quad res */
  1433.     local ip;        /* initial Blum prime 'p' search value */
  1434.     local iq;        /* initial Blum prime 'q' search value */
  1435.     local ir;        /* initial quadratic residue search value */
  1436.     local rlim;        /* high quadratic res search value */
  1437.  
  1438.     /*
  1439.      * firewall - avoid bogus args and very trivial lengths
  1440.      */
  1441.     /* catch the case of no args - compute a different quadratic residue */
  1442.     if (isnull(seed) && isnull(len1) && isnull(len2)) {
  1443.  
  1444.     /* generate the next quadratic residue */
  1445.     do {
  1446.         newres = cryres(cryrand_p, cryrand_q);
  1447.     } while (newres == cryrand_r);
  1448.     cryrand_r = newres;
  1449.     cryrand_exp = cryrand_r;
  1450.  
  1451.     /* clear the internal bits */
  1452.     cryrand_left = 0;
  1453.     cryrand_bitcnt = 0;
  1454.  
  1455.     /* return the current seed early */
  1456.     return (cry_seed);
  1457.     }
  1458.     if (!isint(seed)) {
  1459.     quit "bad arg: seed arg (1st) must be an integer";
  1460.     }
  1461.     if (param(0) == 4) {
  1462.     if (seed < -1) {
  1463.         quit "bad arg: with 4 args: a seed < -1 is reserved for future use";
  1464.     }
  1465.     } else {
  1466.     if (4 && seed < 0) {
  1467.         quit "bad arg: a seed arg (1st) < 0 is reserved for future use";
  1468.     }
  1469.     }
  1470.  
  1471.     /*
  1472.      * 4 arg case: select or search for 'p', 'q' and 'r' from given values
  1473.      */
  1474.     if (param(0) == 4) {
  1475.  
  1476.     /* set initial values */
  1477.     ip = len1;
  1478.     iq = len2;
  1479.     ir = arg4;
  1480.  
  1481.     /*
  1482.      * Unless prohibited by a seed if -1, force minimum values on
  1483.      * 'ip', 'iq' and 'ir'.
  1484.      */
  1485.     if (seed >= 0) {
  1486.         if (!isint(ip) || ip < 3) {
  1487.            /* smallest Blum prime */
  1488.            ip = 3;
  1489.         }
  1490.         if (!isint(iq) || iq < 3) {
  1491.            /* smallest Blum prime */
  1492.            iq = 3;
  1493.         }
  1494.         if (!isint(ir) || ir < 4) {
  1495.            /* cryres() never selects a value < 4 */
  1496.            ir = 4;
  1497.         }
  1498.     }
  1499.  
  1500.     /*
  1501.      * Determine our prime search points
  1502.      */
  1503.     if (seed > 0) {
  1504.         /* add in a random value */
  1505.         oldseed = srand(seed);
  1506.         ip += rand(ip);
  1507.         iq += rand(iq);
  1508.     }
  1509.  
  1510.     /*
  1511.      * force ip <= iq
  1512.      */
  1513.     if (ip > iq) {
  1514.         swap(ip, iq);
  1515.     }
  1516.  
  1517.     /*
  1518.      * find the first Blum prime 'p'
  1519.      */
  1520.     if (seed >= 0) {
  1521.         cryrand_p = nxtprime(ip,3,4);
  1522.     } else {
  1523.         /* seed == -1: assume 'ip' is a Blum prime */
  1524.         cryrand_p = ip;
  1525.     }
  1526.  
  1527.     /*
  1528.      * find the 2nd Blum prime 'q' > 'p', if needed
  1529.      */
  1530.     if (seed >= 0) {
  1531.         if (iq <= cryrand_p) {
  1532.         iq = cryrand_p + 2;
  1533.         }
  1534.         cryrand_q = nxtprime(iq,3,4);
  1535.     } else {
  1536.         /* seed == -1: assume 'iq' is a Blum prime */
  1537.         cryrand_q = iq;
  1538.     }
  1539.  
  1540.     /* remember our p*q Blum prime product as well */
  1541.     cryrand_n = cryrand_p*cryrand_q;
  1542.  
  1543.     /*
  1544.      * search for a quadratic residue
  1545.      */
  1546.     if (seed >= 0) {
  1547.  
  1548.         /* add in a random value to 'ir' if seeded */
  1549.         if (seed > 0) {
  1550.         ir += rand(ir);
  1551.         }
  1552.  
  1553.         /* 
  1554.          * increment until we find a quadratic value
  1555.          *
  1556.          * p is prime and J(r,p) == 1  ==>  r is a quadratic residue of p
  1557.          * q is prime and J(q,p) == 1  ==>  r is a quadratic residue of q
  1558.          *
  1559.          * J(r,p)*J(r,q) == J(r,p*q)
  1560.          * J(r,p) and J(q,p) == 1       ==>  J(r,p*q) == 1
  1561.          * J(r,p*q) == 1           ==>  r is a quadratic residue of p*q
  1562.          *
  1563.          * Try to avoid trivial quadratic residues by forcing the search
  1564.          * over the interval [4, n-3).
  1565.          */
  1566.         rlim = cryrand_n-3;
  1567.         /* if ir is too big, drop down to the bottom of the range */
  1568.         if (ir >= rlim) {
  1569.         ir = 4;
  1570.         }
  1571.         while (jacobi(ir,cryrand_p) != 1 || jacobi(ir,cryrand_q) != 1) {
  1572.         /* if ir is too big, drop down to the bottom of the range */
  1573.         if (++ir >= rlim) {
  1574.             ir = 4;
  1575.         }
  1576.         }
  1577.     }
  1578.     cryrand_r = ir;
  1579.  
  1580.     /* 
  1581.      * clear the previously unused cryrand bits & other misc setup
  1582.      */
  1583.     cryrand_left = 0;
  1584.     cryrand_bitcnt = 0;
  1585.     cryrand_exp = cryrand_r;
  1586.  
  1587.     /* 
  1588.      * reseed the generator, if needed
  1589.      *
  1590.      * The crypto generator no longer needs the additive 55 and shuffle
  1591.      * generators.  We however, restore the additive 55 and shuffle
  1592.      * generators back to its seeded state in order to be sure that it
  1593.      * will be left in the same state.
  1594.      *
  1595.      * This will make more reproducible, calls to the additive 55 and
  1596.      * shuffle generator; or more reproducible, calls to this function
  1597.      * without args.
  1598.      */
  1599.     if (seed > 0) {
  1600.         ir = srand(seed);   /* ignore this return value */
  1601.         return(oldseed);
  1602.     } else {
  1603.         /* no seed change, return the current seed */
  1604.         return (cry_seed);
  1605.     }
  1606.     }
  1607.  
  1608.     /*
  1609.      * If not the 4 arg case:
  1610.      *
  1611.      * convert explicit -1 args into default values
  1612.      * convert missing args into -1 values (use precomputed tables)
  1613.      */
  1614.     if ((isint(len1) && len1 != -1 && len1 < 4) ||
  1615.     (isint(len2) && len2 != -1 && len2 < 4) ||
  1616.     (!isint(len1) && isint(len2)) ||
  1617.     (isint(len1) && !isint(len2))) {
  1618.     quit "bad args: 2 & 3: if 2nd is given, must be -1 or ints > 3";
  1619.     }
  1620.     if (isint(len1) && len1 == -1) {
  1621.     len1 = 248;    /* default len1 value */
  1622.     }
  1623.     if (isint(len2) && len2 == -1) {
  1624.     len2 = 264;    /* default len2 value */
  1625.     }
  1626.     if (!isint(len1) && !isint(len2)) {
  1627.     /* from here down, -1 means use precomputed values */
  1628.     len1 = -1;
  1629.     len2 = -1;
  1630.     }
  1631.  
  1632.     /*
  1633.      * force len1 <= len2
  1634.      */
  1635.     if (len1 > len2) {
  1636.     swap(len1, len2);
  1637.     }
  1638.  
  1639.     /*
  1640.      * seed the generator
  1641.      */
  1642.     oldseed = srand(seed);
  1643.  
  1644.     /*
  1645.      * generate p and q Blum primes
  1646.      *
  1647.      * The Blum process requires the primes to be of the form 3 mod 4.
  1648.      * We also generate n=p*q for future reference.
  1649.      *
  1650.      * We make sure that the lengths are the minimum lengths possible.
  1651.      * We want some range to select a random prime from, so we
  1652.      * go at least 3 bits higher, and as much as 3% plus 3 bits
  1653.      * higher.  Since the section is a random, how high really
  1654.      * does not matter that much, but we want to avoid going to
  1655.      * an extreme to keep the execution time from getting too long.
  1656.      *
  1657.      * Finally, we generate a quadratic residue of n=p*q.
  1658.      */
  1659.     if (len1 > 0) {
  1660.     /* generate a pseudo-random prime ~len1 bits long */
  1661.     rval = rand(2^(len1-1), 2^((int(len1*1.03))+3));
  1662.     cryrand_p = nxtprime(rval,3,4);
  1663.     } else {
  1664.     /* use precomputed 'p' value */
  1665.     cryrand_p = cryrand_init_p;
  1666.     }
  1667.     if (len2 > 0) {
  1668.     /* generate a pseudo-random prime ~len1 bits long */
  1669.     rval = rand(2^(len2-1), 2^((int(len2*1.03))+3));
  1670.     cryrand_q = nxtprime(rval,3,4);
  1671.     } else {
  1672.     /* use precomputed 'q' value */
  1673.     cryrand_q = cryrand_init_q;
  1674.     }
  1675.  
  1676.     /*
  1677.      * find the quadratic residue
  1678.      */
  1679.     cryrand_n = cryrand_p*cryrand_q;
  1680.     cryrand_r = cryres(cryrand_p, cryrand_q);
  1681.  
  1682.     /* 
  1683.      * clear the previously unused cryrand bits & other misc setup
  1684.      */
  1685.     cryrand_left = 0;
  1686.     cryrand_bitcnt = 0;
  1687.     cryrand_exp = cryrand_r;
  1688.  
  1689.     /*
  1690.      * reseed the generator
  1691.      *
  1692.      * The crypto generator no longer needs the additive 55 and shuffle
  1693.      * generators.  We however, restore the additive 55 and shuffle
  1694.      * generators back to its seeded state in order to be sure that it
  1695.      * will be left in the same state.
  1696.      *
  1697.      * This will make more reproducible, calls to the additive 55 and
  1698.      * shuffle generator; or more reproducible, calls to this function
  1699.      * without args.
  1700.      */
  1701.     /* we do not care about this old seed */
  1702.     rval = srand(seed);
  1703.  
  1704.     /*
  1705.      * return the old seed
  1706.      */
  1707.     return(oldseed);
  1708. }
  1709.  
  1710.  
  1711. /*
  1712.  * random - a cryptographically strong pseudo-random number generator
  1713.  *
  1714.  * usage:
  1715.  *    random()     - generate a pseudo-random integer >=0 and < 2^64
  1716.  *    random(a)     - generate a pseudo-random integer >=0 and < a
  1717.  *    random(a,b)    - generate a pseudo-random integer >=a and <= b
  1718.  *
  1719.  * returns:
  1720.  *    a large cryptographically strong pseudo-random number  (see usage)
  1721.  *
  1722.  * This function is just another interface to the crypto generator.
  1723.  * (see the cryrand() function).
  1724.  *
  1725.  * When no arguments are given, a pseudo-random number in the half open
  1726.  * interval [0,2^64) is produced.  This form is identical to calling
  1727.  * cryrand(64).
  1728.  *
  1729.  * When 1 argument is given, a pseudo-random number in the half open interval
  1730.  * [0,a) is produced.
  1731.  *
  1732.  * When 2 arguments are given, a pseudo-random number in the closed interval
  1733.  * [a,b] is produced.
  1734.  *
  1735.  * This generator uses the crypto to return a large pseudo-random number.
  1736.  *
  1737.  * The input values a and b, if given, must be integers.
  1738.  *
  1739.  * Internally, bits are produced log2(log2(n=p*q)) at a time.  If a
  1740.  * call to this function does not exhaust all of the collected bits,
  1741.  * the unused bits will be saved away and used at a later call.
  1742.  * Setting the seed via scryrand(), srandom() or cryrand(len,1)
  1743.  * will clear out all unused bits.
  1744.  *
  1745.  * NOTE: The BSD random() function returns only 31 bits, while we return 64.
  1746.  *
  1747.  * NOTE: This function is the Blum cryptographically strong
  1748.  *     pseudo-random number generator!
  1749.  */
  1750. define
  1751. random(a,b)
  1752. {
  1753.     local range;        /* we must generate [0,range) first */
  1754.     local offset;        /* what to add to get a adjusted range */
  1755.     local rangebits;        /* the number of bits in range */
  1756.     local ret;            /* pseudo-random bit value */
  1757.  
  1758.     /*
  1759.      * setup and special cases
  1760.      */
  1761.     /* deal with the rand() case */
  1762.     if (isnull(a) && isnull(b)) {
  1763.     /* no args means return 64 bits */
  1764.     return(cryrand(64));
  1765.     }
  1766.     /* firewall - args, if given must be in integers */
  1767.     if (!isint(a) || (!isnull(b) && !isint(b))) {
  1768.     quit "bad args: args, if given, must be integers";
  1769.     }
  1770.     /* convert rand(x) into rand(0,x-1) */
  1771.     if (isnull(b)) {
  1772.     /* convert call into a closed interval */
  1773.     b = a-1;
  1774.     a = 0;
  1775.     /* firewall - rand(0) should act like rand(0,0) */
  1776.     if (b == -1) {
  1777.         return(0);
  1778.     }
  1779.     }
  1780.     /* determine the range and offset */
  1781.     if (a >= b) {
  1782.     /* deal with the case of rand(a,a) */
  1783.     if (a == b) {
  1784.         /* not very random, but it is true! */
  1785.         return(a);
  1786.     }
  1787.     range = a-b+1;
  1788.     offset = b;
  1789.     } else {
  1790.     /* convert random(a,b), where a<b, into random(b,a) */
  1791.     range = b-a+1;
  1792.     offset = a;
  1793.     }
  1794.     rangebits = highbit(range-1)+1;
  1795.     /*
  1796.      * At this point, we seek a pseudo-random number [0,range) to which
  1797.      * we will add offset to produce a number [offset,range+offset).
  1798.      */
  1799.  
  1800.     /*
  1801.      * loop until we get a value that is in range
  1802.      *
  1803.      * We will obtain pseudo-random values over the range [0,2^rangebits)
  1804.      * where 2^rangebits >= range and 2^(rangebits-1) < range.  We
  1805.      * will ignore any results that are > the range that we want.
  1806.      *
  1807.      * A note in modulus biasing:
  1808.      *
  1809.      * We will not fall into the trap of thinking that we can simply take
  1810.      * a value mod 'range'.  Consider the case where 'range' is '80'
  1811.      * and we are given pseudo-random numbers [0,100).  If we took them
  1812.      * mod 80, then the numbers [0,20) would be produced more often
  1813.      * because the numbers [81,100) mod 80 wrap back into [0,20).
  1814.      */
  1815.     do {
  1816.     /* obtain a pseudo-random value */
  1817.     ret = cryrand(rangebits);
  1818.     } while (ret >= range);
  1819.  
  1820.     /*
  1821.      * return the adjusted range value
  1822.      */
  1823.     return(ret+offset);
  1824. }
  1825.  
  1826.  
  1827. /*
  1828.  * srandom - seed the cryptographically strong pseudo-random number generator
  1829.  *
  1830.  * given:
  1831.  *    seed    a random number seed
  1832.  *
  1833.  * returns:
  1834.  *      the previous seed
  1835.  *
  1836.  * This function is just another interface to the crypto generator.
  1837.  * (see the scryrand() function).
  1838.  *
  1839.  * This function makes indirect use of the additive 55 and shuffle 
  1840.  * generator.
  1841.  *
  1842.  * There is no limit on the size of a seed.  On the other hand,
  1843.  * extremely large seeds require large tables and long seed times.
  1844.  * Using a seed in the range of [2^64, 2^64 * 128!) should be
  1845.  * sufficient for most purposes.  An easy way to stay within this
  1846.  * range to to use seeds that are between 21 and 215 digits long, or
  1847.  * 64 to 780 bits long.
  1848.  *
  1849.  * NOTE: Calling this function will clear any internally buffer bits.
  1850.  *     See cryrand() for details.
  1851.  *
  1852.  * NOTE: This function seeds the Blum cryptographically strong
  1853.  *     pseudo-random number generator!
  1854.  */
  1855. define
  1856. srandom(seed)
  1857. {
  1858.     if (!isint(seed)) {
  1859.     quit "bad arg: seed must be an integer";
  1860.     }
  1861.     if (seed < 0) {
  1862.     quit "bad arg: seed < 0 is reserved for future use";
  1863.     }
  1864.     return(scryrand(seed));
  1865. }
  1866.  
  1867.  
  1868. /*
  1869.  * randstate - set/get the state of all of the generators
  1870.  *
  1871.  * usage:
  1872.  *    randstate()    return the current state
  1873.  *    randstate(0)    return the previous state, set the default state
  1874.  *    randstate(cobj)    return the previous state, set a new state
  1875.  *
  1876.  * In the first form: randstate()
  1877.  *
  1878.  *    This function returns an cryobj object containing information
  1879.  *    about the current state of all of the generators.
  1880.  *
  1881.  * In the second form: randstate(0)
  1882.  *
  1883.  *    This function sets all of the generators to the default initial
  1884.  *    state (i.e., the state when this library was loaded).
  1885.  *
  1886.  *    This function returns an cryobj object containing information
  1887.  *    about the previous state of all of the generators.
  1888.  *
  1889.  * In the third form: randstate(cobj)
  1890.  *
  1891.  *    This function sets all of the generators to the state as found
  1892.  *    in the cryobj object.
  1893.  *
  1894.  *    This function returns an cryobj object containing information
  1895.  *    about the previous state of all of the generators.
  1896.  *
  1897.  * This function may be used to save and restore cryrand() & random()
  1898.  * generator states.  For example:
  1899.  *
  1900.  *    state = randstate()        <-- save the current state
  1901.  *    random()            <-- print the next 64 bits
  1902.  *    randstate(state)        <-- restore previous state
  1903.  *    random()            <-- print the same 64 bits
  1904.  *
  1905.  * One may quickly reseed a generator.  For example:
  1906.  *
  1907.  *    srandom(1,330,350)        <-- seed the generator
  1908.  *    seed1state = randstate()    <-- remember this 1st seeded state
  1909.  *    random()            <-- print 1st 64 bits seed 1 generator
  1910.  *    srandom(2,331,351)        <-- seed the generator again
  1911.  *    seed2state = randstate()    <-- remember this 2nd seeded state
  1912.  *    random()            <-- print 1st 64 bits seed 2 generator
  1913.  *
  1914.  *    randstate(seed1state)        <-- reseed to the 1st seeded state
  1915.  *    random()            <-- reprint 1st 64 bits seed 1 generator
  1916.  *    randstate(seed2state)        <-- reseed to the 2nd seeded state
  1917.  *    random()            <-- reprint 1st 64 bits seed 2 generator
  1918.  *
  1919.  *    oldstate = randstate(0)        <-- seed to the default generator
  1920.  *    random()            <-- print 1st 64 bits from default
  1921.  *    a55rand()            <-- print 1st 64 bits a55 generator
  1922.  *    prevstate = randstate(oldstate)    <-- restore seed 2 generator
  1923.  *    random()            <-- print 2nd 64 bits seed 2 generator
  1924.  *    randstate(prevstate)        <-- restore def generator in progress
  1925.  *    random()            <-- print 2nd 64 bits default generator
  1926.  *    a55rand()            <-- print 2nd 64 bits a55 generator
  1927.  *
  1928.  * given:
  1929.  *    cobj    if a cryobj object, use that object to set the current state
  1930.  *        if 0, set to the default state
  1931.  *
  1932.  * return:
  1933.  *    return the state of the crypto pseudo-random number generator in
  1934.  *           the form of an cryobj object, as it was prior to this call
  1935.  *
  1936.  * NOTE: No checking is performed on the data the 3rd form (cryobj object
  1937.  *     arg) is used.  The user must ensure that the arg represents a valid
  1938.  *     generator state.
  1939.  *
  1940.  * NOTE: When using the second form (passing an integer arg), only 0 is
  1941.  *     defined.  All other integer values are reserved for future use.
  1942.  */
  1943. define
  1944. randstate(arg)
  1945. {
  1946.     /* declare our objects */
  1947.     local obj cryobj x;        /* firewall comparator */
  1948.     local obj cryobj prev;    /* previous states of the generators */
  1949.     local junk;            /* dummy holder of random values */
  1950.  
  1951.     /* firewall */
  1952.     if (!isint(arg) && !istype(arg,x) && !isnull(arg)) {
  1953.     quit "bad arg: argument must be integer, an cryobj object or missing";
  1954.     }
  1955.     if (isint(arg) && arg != 0) {
  1956.         quit "bad arg:  non-zero integer arguments are reserved for future use";
  1957.     }
  1958.  
  1959.     /*
  1960.      * save the current state
  1961.      */
  1962.     prev.p = cryrand_p;
  1963.     prev.q = cryrand_q;
  1964.     prev.r = cryrand_r;
  1965.     prev.exp = cryrand_exp;
  1966.     prev.left = cryrand_left;
  1967.     prev.bitcnt = cryrand_bitcnt;
  1968.     prev.a55j = add55_j;
  1969.     prev.a55k = add55_k;
  1970.     prev.seed = cry_seed;
  1971.     prev.shufy = shuf_y;
  1972.     prev.shufsz = shuf_size;
  1973.     prev.shuftbl = shuf_tbl;
  1974.     prev.a55tbl = add55_tbl;
  1975.     if (isnull(x)) {
  1976.     /* if no args, just return current state */
  1977.     return (prev);
  1978.     }
  1979.  
  1980.     /*
  1981.      * deal with the cryobj arg - set the state
  1982.      */
  1983.     if (istype(arg, x)) {
  1984.     /* set the state from this object */
  1985.     cryrand_p = arg.p;
  1986.     cryrand_q = arg.q;
  1987.     cryrand_n = cryrand_p*cryrand_q;
  1988.     cryrand_r = arg.r;
  1989.     cryrand_exp = arg.exp;
  1990.     cryrand_left = arg.left;
  1991.     cryrand_bitcnt = arg.bitcnt;
  1992.     add55_j = arg.a55j;
  1993.     add55_k = arg.a55k;
  1994.     cry_seed = arg.seed;
  1995.     add55_seed64 = randreseed64(cry_seed);
  1996.     shuf_y = arg.shufy;
  1997.     shuf_size = arg.shufsz;
  1998.     shuf_shift = (64-highbit(shuf_size));
  1999.     mat shuf_tbl[shuf_size];
  2000.     shuf_tbl = arg.shuftbl;
  2001.     add55_tbl = arg.a55tbl;
  2002.  
  2003.     /*
  2004.      * deal with the 0 integer arg - set the default initial state
  2005.      */
  2006.     } else if (isint(arg) && arg == 0) {
  2007.     cryrand_p = cryrand_init_p;
  2008.     cryrand_q = cryrand_init_q;
  2009.     cryrand_n = cryrand_p * cryrand_q;
  2010.     cryrand_r = cryrand_init_r;
  2011.     cryrand_exp = cryrand_r;
  2012.     cryrand_left = 0;
  2013.     cryrand_bitcnt = 0;
  2014.     cry_seed = 0;
  2015.     cry_seed = sshufrand(0);
  2016.     }
  2017.  
  2018.     /*
  2019.      * return the previous state
  2020.      */
  2021.     return (prev);
  2022. }
  2023.  
  2024.  
  2025. /*
  2026.  * nxtprime - find a probable prime >= n_arg
  2027.  *
  2028.  * usage:
  2029.  *    nxtprime(n_arg)
  2030.  *    nxtprime(n_arg, modval, modulus)
  2031.  *
  2032.  * given:
  2033.  *    n_arg            lower bound of the search
  2034.  *    [modval modulus]    if given, look for numbers mod modulus == modval
  2035.  *
  2036.  * returns:
  2037.  *    A number is that is very likely prime.
  2038.  *
  2039.  * In the first case 'nxtprime(n_arg)', this function returns a probable
  2040.  * prime >= n_arg.  In the second case 'nxtprime(n_arg, v, u)', this
  2041.  * function returns a probable prime >= n_arg that is also == v mod u.
  2042.  *
  2043.  * This function will not skip over a prime, through there is a
  2044.  * extremely unlikely chance that it will return a composite.
  2045.  * The odds that a number returned by this function is not prime
  2046.  * are 1 in 4^50.  The failure rate of this function is many orders
  2047.  * or magnitude lower than the failure rate due to a hardware error.
  2048.  *
  2049.  * NOTE: This function can take a long time, given a large value of n_arg.
  2050.  */
  2051. define
  2052. nxtprime(n_arg, modval, modulus)
  2053. {
  2054.     local modgcd;        /* gcd(modulus,modval) */
  2055.     local n;            /* value >= n_arg that is being tested */
  2056.     local j;
  2057.  
  2058.     /*
  2059.      * firewall
  2060.      */
  2061.     if (!isint(n_arg)) {
  2062.     quit "bad args: 1st arg must be an integer";
  2063.     }
  2064.     if (!isnull(modulus) && !isint(modval)) {
  2065.     quit "bad args: 3rd arg, if 2nd arg is given, must be an integer";
  2066.     }
  2067.     if (!isnull(modulus) && (!isint(modulus) || modulus <= 0)) {
  2068.     quit "bad args: 3nd arg, if given, must be an integer > 0";
  2069.     }
  2070.  
  2071.     /*
  2072.      * get values < 3 out of the way
  2073.      */
  2074.     n = n_arg;
  2075.     if (n < 3) {
  2076.     /* get the even prime out of the way, if possible */
  2077.     if (isnull(modulus) ||
  2078.         modulus == 1 ||
  2079.         (n%modulus == modval%modulus)) {
  2080.         /*
  2081.          * 2 is the greatest odd prime, because
  2082.          * 2 is the least even prime  :-)
  2083.          */
  2084.         return(2);
  2085.     }
  2086.     /* we have eliminated everything < 3 */
  2087.     n = 3;
  2088.     }
  2089.  
  2090.     /*
  2091.      * convert nxtprime(n) to nxtprime(n,1,2)
  2092.      * convert nxtprime(n,x,1) to nxtprime(n,1,2)
  2093.      * convert nxtprime(n,a,b) to nxtprime(n,a mod b,b)
  2094.      */
  2095.     if (isnull(modulus) || modulus < 2) {
  2096.     modulus = 2;
  2097.     modval = 1;
  2098.     }
  2099.     modval %= modulus;
  2100.  
  2101.     /*
  2102.      * catch cases where no more primes == 'modval' mod 'modulus' exist
  2103.      */
  2104.     modgcd = gcd(modval,modulus);
  2105.     if (modgcd > 1) {
  2106.  
  2107.     /* if beyond the modgcd, then no primes can exist */
  2108.         if (n > modgcd) {
  2109.         print "n_arg:",n_arg,"  modval:",modval,"  modulus:",modulus;
  2110.         quit "no such prime of that form exists";
  2111.     }
  2112.  
  2113.     /* else n <= modgcd, then our only chance is if modgcd is prime */
  2114.     /* reject if modgcd has an obvious prime factor */
  2115.     if (modgcd > 10 && gcd(modgcd,nxtprime_pfact10) != 1) {
  2116.         print "n_arg:",n_arg,"  modval:",modval,"  modulus:",modulus;
  2117.         quit "no such prime of that form exists";
  2118.     }
  2119.     if (modgcd > 100 && gcd(modgcd,nxtprime_pfact100) != 1) {
  2120.         print "n_arg:",n_arg,"  modval:",modval,"  modulus:",modulus;
  2121.         quit "no such prime of that form exists";
  2122.     }
  2123.     if (modgcd > 1000 && gcd(modgcd,nxtprime_pfact1000) != 1) {
  2124.         print "n_arg:",n_arg,"  modval:",modval,"  modulus:",modulus;
  2125.         quit "no such prime of that form exists";
  2126.     }
  2127.  
  2128.     /* do 50 probable prime tests, for a 1 in 4^50 false prime rate */
  2129.     if (!ptest(modgcd,50)) {
  2130.         print "n_arg:",n_arg,"  modval:",modval,"  modulus:",modulus;
  2131.         quit "no such prime of that form exists";
  2132.     }
  2133.  
  2134.     /* modgcd is the only prime >= n */
  2135.     return(modgcd);
  2136.     }
  2137.  
  2138.     /*
  2139.      * bump n up to the next possible case
  2140.      *
  2141.      * n will be an odd number == 'modval' mod 'modulus'
  2142.      */
  2143.     if (n%modulus != modval) {
  2144.     j = n - (n%modulus) + modval;
  2145.     if (j < n) {
  2146.         n = j+modulus;
  2147.     } else {
  2148.         n = j;
  2149.     }
  2150.     }
  2151.     if (n%2 == 0) {
  2152.     n += modulus;
  2153.     }
  2154.  
  2155.     /* look for a prime */
  2156.     n = n-modulus;
  2157.     do {
  2158.     /* try the next integer */
  2159.     n = n+modulus;
  2160.  
  2161.     /* reject if it has an obvious prime factor */
  2162.     if (n > 10 && gcd(n,nxtprime_pfact10) != 1) {
  2163.         continue;
  2164.     }
  2165.     if (n > 100 && gcd(n,nxtprime_pfact100) != 1) {
  2166.         continue;
  2167.     }
  2168.     if (n > 1000 && gcd(n,nxtprime_pfact1000) != 1) {
  2169.         continue;
  2170.     }
  2171.  
  2172.     /* do 50 probable prime tests */
  2173.     if (!ptest(n,50)) {
  2174.         continue;
  2175.     }
  2176.  
  2177.     /* n is very likely a prime number */
  2178.     return(n);
  2179.  
  2180.     } while (1);
  2181. }
  2182.  
  2183.  
  2184. /*
  2185.  * cryobj - how to initialize a cryobj object
  2186.  *
  2187.  * given:
  2188.  *    p        first Blum prime (prime 3 mod 4)
  2189.  *    q        second Blum prime (prime 3 mod 4)
  2190.  *    r        quadratic residue of n=p*q
  2191.  *    exp        used in computing crypto good bits
  2192.  *    left        bits unused from the last cryrand() call
  2193.  *    bitcnt        left contains bitcnt crypto good bits
  2194.  *    a55j        1st additive 55 table pointer
  2195.  *    a55k        2nd additive 55 table pointer
  2196.  *    seed        last seed set by sa55rand() or 0
  2197.  *    shufy        Y (previous a55rand() output for shuffle)
  2198.  *    shufsz        size of the shuffle table
  2199.  *    shuftbl        a matrix of shufsz entries
  2200.  *    a55tbl        additive 55 generator state table
  2201.  *
  2202.  * return:
  2203.  *    an cryobj object
  2204.  *
  2205.  * NOTE: This function, by convention, returns an cryobj object.
  2206.  */
  2207. define
  2208. cryobj(p,q,r,exp,left,bitcnt,a55j,a55k,seed,shufy,shufsz,shuftbl,a55tbl)
  2209. {
  2210.     /* declare our objects */
  2211.     local obj cryobj x;
  2212.  
  2213.     /* firewall */
  2214.     if (!isint(p) || !isint(q) || !isint(r) || !isint(exp) || \
  2215.     !isint(left) || !isint(bitcnt) || !isint(a55j) || \
  2216.     !isint(a55k) || !isint(seed) || !isint(shufy) || !isint(shufsz)) {
  2217.     quit "bad args: first 11 args must be integers";
  2218.     }
  2219.     if (!ismat(shuftbl) || matdim(shuftbl) != 1 || \
  2220.     matmin(shuftbl,1) != 0 || matmax(shuftbl,1) != shuf_size-1) {
  2221.     quit "bad arg: 12th is not a mat[0:shuf_size-1]";
  2222.     }
  2223.     if (!ismat(a55tbl) || matdim(a55tbl) != 1 || \
  2224.     matmin(a55tbl,1) != 0 || matmax(a55tbl,1) != 54) {
  2225.     quit "bad arg: 13th is not a mat[0:54]";
  2226.     }
  2227.  
  2228.     /* initialize object with default startup values */
  2229.     x.p = p;
  2230.     x.q = q;
  2231.     x.r = r;
  2232.     x.exp = exp;
  2233.     x.left = left;
  2234.     x.bitcnt = bitcnt;
  2235.     x.a55j = a55j;
  2236.     x.a55k = a55k;
  2237.     x.seed = seed;
  2238.     x.shufy = shuf_y;
  2239.     x.shufsz = shuf_size;
  2240.     x.shuftbl = shuf_tbl;
  2241.     x.a55tbl = a55tbl;
  2242.  
  2243.     /* return the initialized object */
  2244.     return (x);
  2245. }
  2246.  
  2247.  
  2248. /*
  2249.  * cryobj_print - print the value of a cryobj object
  2250.  *
  2251.  * usage:
  2252.  *    a    an cryobj object
  2253.  *
  2254.  * NOTE: This function is called automatically when an cryobj object
  2255.  *       is displayed.
  2256.  */
  2257. define
  2258. cryobj_print(a)
  2259. {
  2260.     /* declare our objects */
  2261.     local obj cryobj x;        /* firewall comparator */
  2262.  
  2263.     /* firewall */
  2264.     if (!istype(a, x)) {
  2265.     quit "bad arg: arg is not an cryobj object";
  2266.     }
  2267.     if (!ismat(a.shuftbl) || matdim(a.shuftbl) != 1 || \
  2268.     matmin(a.shuftbl,1) != 0 || matmax(a.shuftbl,1) != a.shufsz-1) {
  2269.     quit "bad arg: 12th is not a mat[0:shuf_size-1]";
  2270.     }
  2271.     if (!ismat(a.a55tbl) || matdim(a.a55tbl) != 1 || \
  2272.     matmin(a.a55tbl,1) != 0 || matmax(a.a55tbl,1) != 54) {
  2273.     quit "bad arg: 13th is not a mat[0:54]";
  2274.     }
  2275.  
  2276.     /* print the value */
  2277.     print "cryobj(" : a.p : "," : a.q : "," : a.r : "," : a.exp : "," : \
  2278.       a.left : "," : a.bitcnt : "," : a.a55j : "," : a.a55k : "," : \
  2279.       a.seed : "," : a.shufy : "," : a.shufsz : \
  2280.       ",[" : a.shuftbl[0] : "," : a.shuftbl[1] : "," : \
  2281.       a.shuftbl[2] : ",...," : a.shuftbl[52] : "," : \
  2282.       a.shuftbl[53] : "," : a.shuftbl[54] : "]" : \
  2283.       ",[" : a.a55tbl[0] : "," : a.a55tbl[1] : "," : \
  2284.       a.a55tbl[2] : ",...," : a.a55tbl[52] : "," : \
  2285.       a.a55tbl[53] : "," : a.a55tbl[54] : "])" : ;
  2286. }
  2287.  
  2288.  
  2289. /*
  2290.  * cryres - find a pseudo-random quadratic residue for scryrand() and cryrand()
  2291.  *
  2292.  * given:
  2293.  *    p    first prime
  2294.  *    q    second prime
  2295.  *
  2296.  * returns:
  2297.  *    a number that is a quadratic residue of n=p*q
  2298.  *
  2299.  * This function is returns the pseudo-random quadratic residue of
  2300.  * the product of two primes.  Normally this function is called
  2301.  * only by the crypto generator.
  2302.  *
  2303.  * NOTE: No check is made to ensure that the values passed are primes.
  2304.  *
  2305.  * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  2306.  *       generate some internal values.
  2307.  */
  2308. define
  2309. cryres(p,q)
  2310. {
  2311.     local rval;        /* a temporary pseudo-random value */
  2312.     local sqrpow;    /* a power of 2 starting > n^(3/4) */
  2313.     local quadres;    /* 0 or a quadratic residue of n = p*q */
  2314.     local n;        /* n=p*q */
  2315.     local j;
  2316.  
  2317.     /*
  2318.      * firewall
  2319.      */
  2320.     if (!isint(p) || !isint(q) || p < 3 || q < 3) {
  2321.     quit "bad args: p and q must be integers > 2";
  2322.     }
  2323.  
  2324.     /*
  2325.      * find a pseudo-random quadratic residue of n = p*q
  2326.      *
  2327.      * To find a pseudo-random quadratic residue, we will generate
  2328.      * pseudo-random numbers to try in the interval [2^sqrpow,n-3),
  2329.      * where 2^sqrpow is the first power of 2 > n^(3/4).  This range
  2330.      * helps us avoid selecting trivial residues abs(quadres mod n=p*q)
  2331.      * is tiny.  We will never select a residue < 4.
  2332.      *
  2333.      * When we fail to find a quadratic residue after 1009 tries, we will
  2334.      * drop sqrpow by 1 and start at another pseudo-random location.
  2335.      *
  2336.      * It is very unlikely that we will need to search more than a
  2337.      * few numbers to find a quadratic residue of n = p*q.
  2338.      *
  2339.      * We will reject any quadratic residue that is a square of
  2340.      * itself, mod n=p*q.
  2341.      */
  2342.     n = p*q;
  2343.     quadres = 0;
  2344.     sqrpow = highbit(n)//4*3;
  2345.     do {
  2346.     /* generate a pseudo-random starting point */
  2347.     rval = rand(2^sqrpow, n-4);
  2348.  
  2349.     /* look for 1009 times or until >= cryrand_n */
  2350.     for (j=0; j < 1009; ++j, ++rval) {
  2351.  
  2352.         /*
  2353.          * check if we have a quadratic residue of n = p*q
  2354.          *
  2355.          * p is prime and J(r,p) == 1  ==>  r is a quadratic residue of p
  2356.          * q is prime and J(q,p) == 1  ==>  r is a quadratic residue of q
  2357.          *
  2358.          * J(r,p)*J(r,q) == J(r,p*q)
  2359.          * J(r,p) and J(q,p) == 1       ==>  J(r,p*q) == 1
  2360.          * J(r,p*q) == 1           ==>  r is a quadratic residue of p*q
  2361.          */
  2362.         if (jacobi(rval,p) == 1 && jacobi(rval,q) == 1) {
  2363.         quadres = rval;
  2364.         break;
  2365.         }
  2366.     }
  2367.  
  2368.     /* setup for a new pseudo-random starting point if we found nothing */
  2369.     if (quadres == 0) {
  2370.         /* reduce sqrpow if reasonable */
  2371.         if (sqrpow > 2) {
  2372.         --sqrpow;
  2373.         }
  2374.     }
  2375.     } while (quadres == 0 || ((quadres^2)%n) == quadres);
  2376.  
  2377.     /*
  2378.      * return the quadratic residue of n = p*q
  2379.      */
  2380.     return (quadres);
  2381. }
  2382.  
  2383.  
  2384. /*
  2385.  * randreseed64 - scramble a 64 bit seed
  2386.  *
  2387.  * given:
  2388.  *    a 64 bit seed
  2389.  *
  2390.  * returns:
  2391.  *    a 64 scrambled seed, or 0 if seed was 0
  2392.  *
  2393.  * It is 'nice' when a seed of "n" produces a 'significantly different'
  2394.  * sequence than a seed of "n+1".  Generators, by convention, assign
  2395.  * special significance to the seed of '0'.  It is an unfortunate that
  2396.  * people often pick small seed values, particularly when large seed
  2397.  * are of significance to the generators found in this file.
  2398.  *
  2399.  * If 'seed' is 0, then 0 is returned.  If 'seed' is non-zero, we will
  2400.  * produce a different and unique new scrambled 'seed'.  This scrambling
  2401.  * will effectively eliminate the human factors and perceptions that
  2402.  * are noted above.
  2403.  *
  2404.  * It should be noted that the purpose of this process to scramble a seed
  2405.  * ONLY.  We do not care if these generators produce good random numbers.
  2406.  * We only want to help eliminate the human factors and perceptions
  2407.  * noted above.
  2408.  *
  2409.  * This function scrambles the low 64 bits of a seed, by mapping [0,2^64)
  2410.  * into [0,2^64).  This map is one-to-one and onto.  Mapping is performed
  2411.  * using  a linear congruence generator of the form:
  2412.  *
  2413.  *        X1 <-- (a*X0 + c) mod m
  2414.  *
  2415.  * The generator are based on the linear congruential generators found in
  2416.  * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  2417.  * vol 2, 2nd edition (1981), Section 3.6, pages 170-171.
  2418.  *
  2419.  * Because we process 64 bits we will take:
  2420.  *
  2421.  *        m = 2^64            (based on note ii)
  2422.  *
  2423.  * We will scan the Rand book of numbers to look for an 'a' such that:
  2424.  *
  2425.  *        a mod 8 == 5            (based on note iii)
  2426.  *        0.01*m < a < 0.99*m        (based on note iv)
  2427.  *        0.01*2^64 < a < 0.99*2^64
  2428.  *
  2429.  * To help keep the generators independent, we want:
  2430.  *
  2431.  *        a is prime
  2432.  *
  2433.  * The choice of an adder 'c' is considered immaterial according (based 
  2434.  * in note v).  Knuth suggests 'c==1' or 'c==a'.  We elect to select 'c' 
  2435.  * using the same process as we used to select 'a'.  The choice is 
  2436.  * 'immaterial' after all, and as long as:
  2437.  *
  2438.  *        gcd(c, m) == 1        (based on note v)
  2439.  *        gcd(c, 2^64) == 1
  2440.  *
  2441.  * the concerns are met.   It can be shown that if we have:
  2442.  *
  2443.  *        gcd(a, c) == 1
  2444.  *
  2445.  * then the adders and multipliers will be more independent.
  2446.  *
  2447.  * We will obtain the values 'a' and 'c for our generator from the 
  2448.  * Rand book of numbers.  Because m=2^64 is 20 decimal digits long, we 
  2449.  * will search the Rand book of numbers 20 at a time.  We will skip any 
  2450.  * of the 55 values that were used to initialize the additive 55 generators. 
  2451.  * The values obtained from the Rand book are:
  2452.  *
  2453.  *        a = 6316878969928993981
  2454.  *        c = 1363042948800878693
  2455.  *
  2456.  * As we stated before, we must map 0 ==> 0.  The linear congruence
  2457.  * generator would normally map as follows:
  2458.  *
  2459.  *    0 ==> 1363042948800878693    (0 ==> c)
  2460.  *
  2461.  * To determine which value maps back into 0, we compute:
  2462.  *
  2463.  *    (-c*minv(a,m)) % m
  2464.  *
  2465.  * and thus we find that the congruence generator would also normally map:
  2466.  *
  2467.  *    10239951819489363767 ==> 0
  2468.  *
  2469.  * To overcome this, and preserve the 1-to-1 and onto map, we force:
  2470.  *
  2471.  *    0 ==> 0
  2472.  *    10239951819489363767 ==> 1363042948800878693
  2473.  *
  2474.  * To repeat, this function converts a values into a seed value.  With the
  2475.  * except of 'seed == 0', every value is mapped into a unique seed value.
  2476.  * This mapping need not be complex, random or secure.  All we attempt
  2477.  * to do here is to allow humans who pick small or successive seed values
  2478.  * to obtain reasonably different sequences from the generators below.
  2479.  *
  2480.  * NOTE: This is NOT a random number generator.  This function is intended
  2481.  *     to be used internally by sa55rand() and sshufrand().
  2482.  */
  2483. define
  2484. randreseed64(seed)
  2485. {
  2486.     local ret;            /* return value */
  2487.     local a;            /* generator 0 multiplier */
  2488.     local c;            /* generator 0 adder */
  2489.  
  2490.     /* firewall */
  2491.     if (!isint(seed)) {
  2492.     quit "bad args: seed must be an integer";
  2493.     }
  2494.     if (seed < 0) {
  2495.     quit "bad arg: seed < 0 is reserved for future use";
  2496.     }
  2497.  
  2498.     /* if seed is 0, we will return 0 */
  2499.     if (seed == 0) {
  2500.     return (0);
  2501.     }
  2502.  
  2503.     /*
  2504.      * process the low 64 bits of the seed
  2505.      */
  2506.     a = 6316878969928993981;
  2507.     c = 1363042948800878693;
  2508.     ret = (((seed & cry_mask)*a + c) & cry_mask);
  2509.  
  2510.     /*
  2511.      * Normally, the above equation would map:
  2512.      *
  2513.      *        f(0) == 1363042948800878693
  2514.      *        f(10239951819489363767) == 0
  2515.      *
  2516.      * However, we have already forced f(0) == 0.  To preserve the
  2517.      * 1-to-1 and onto map property, we force:
  2518.      *
  2519.      *        f(10239951819489363767) ==> 1363042948800878693
  2520.      */
  2521.     if (ret == 0) {
  2522.     ret = c;
  2523.     }
  2524.  
  2525.     /* return the scrambled value */
  2526.     return (ret);
  2527. }
  2528.  
  2529.  
  2530. /*
  2531.  * Initial read execution code
  2532.  */
  2533. cry_seed = srand(0);        /* pre-initialize the tables */
  2534.  
  2535.  
  2536. global lib_debug;
  2537. if (lib_debug >= 0) {
  2538.     print "ver: 10.5 06:19:34 5/9/93";
  2539.     print "shufrand() defined";
  2540.     print "sshufrand(seed) defined";
  2541.     print "rand([a, [b]]) defined";
  2542.     print "srand(seed) defined";
  2543.     print "cryrand([a, [b]]) defined";
  2544.     print "scryrand([seed, [len1, len2]]) defined";
  2545.     print "scryrand(seed, ip, iq, ir) defined";
  2546.     print "random([a, [b]]) defined";
  2547.     print "srandom(seed) defined";
  2548.     print "obj cryobj defined";
  2549.     print "randstate([cryobj | 0]) defined";
  2550.     print "nxtprime(n, [val, modulus]) defined";
  2551. }
  2552.